I am trying to append a character to a string... that works fine unfortunately I can't free the mem of the string afterwards which causes that the string gets longer and longer.... as it reads a file every linie will be added to the string which obviously shouldn't happen
char* append_char(char* string, char character)
{
int length = strlen(string);
string[length] = character;
string[length+1] = '\0';
return string;
}
I allocated mem for string like
char *read_string = (char *)malloc(sizeof(char)*500);
call the function append_char(read_string,buffer[0]);
and free it after the whole string is build free(read_string);
I presume that once I call the append_char() , the mem allocation is going to be changed, which cause that I can't get hold of it.
Edited: here is the function which uses the append_char()
char *read_log_file_row(char *result,int t)
{
filepath ="//home/,,,,,/mmm.txt";
int max = sizeof(char)*2;
char buffer[max];
char *return_fgets;
char *read_string = malloc(sizeof(char)*500);
file_pointer = fopen(filepath,"r");
if(file_pointer == NULL)
{
printf("Didn't work....");
return NULL;
}
int i = 0;
while(i<=t)
{
while(return_fgets = (fgets(buffer, max, file_pointer)))
{
if(buffer[0] == '\n')
{
++i;
break;
}
if(i==t)
{
append_char(read_string,buffer[0]);
}
}
if(return_fgets == NULL)
{
free(read_string);
return NULL;
/* return "\0";*/
}
if(buffer[0] != '\n')
append_char(read_string,buffer[0]);
}
fclose(file_pointer);
strcpy(result,read_string);
free(read_string);
return result;
}