Here is my code:
char* get_string()
{
#define MAX_STRING_LENGTH 1000
char *input=NULL;
char buffer[MAX_STRING_LENGTH];
fgets(buffer,MAX_STRING_LENGTH,stdin);
fflush(stdin);
if((input=realloc(input,strlen(buffer)))==NULL)
{
printf("Error allocating memory for string.");
return NULL;
}
strncpy(input,buffer,sizeof(buffer));
return input;
}
The 1st time I'm calling the function is works OK, the second time it will return garbage and the program exists with some error.
OK so following the suggestions I edited the code:
char* get_string()
{
#define MAX_STRING_LENGTH 1000
char *input=NULL;
char buffer[MAX_STRING_LENGTH];
if(fgets(buffer,MAX_STRING_LENGTH,stdin)==NULL)
{
printf("Error reading string.");
return NULL;
}
if((input=malloc(strlen(buffer)+1))==NULL)
{
printf("Error allocating memory for string.");
return NULL;
}
strncpy(input,buffer,sizeof(input));
return input;
}
In main I have:
while(1)
{
tmp_arr_ptr=get_string();
printf("%s",tmp_arr_ptr);
}
However I see the same behavior as before.
UPDATE - changed to strcpy(input,buffer); and now it works fine!