I'm writing a function which to get the contents of one line of a text file at a time for parsing, without knowing the size of the line. The function works if all I'm doing is getting the lines and printing them, but as soon as I try to allocate memory to another local variable I get the glibc error:
glibc detected *** ./mention: realloc(): invalid next size: 0x00000000010ac250 ***
Specifically, SEARCH_LENGTH is defined as 40 and adding (char * word) causes the error.
void testF(FILE * stream){
char * line = calloc(SEARCH_LENGTH , sizeof(char));
int lineScalar = 1;
char * word = calloc(SEARCH_LENGTH, sizeof(char)); // adding this line causes the error
while(fgets(line, SEARCH_LENGTH + 1, stream)!= NULL){
while((*(line + (SEARCH_LENGTH*lineScalar -1)) != '\0') && (*(line + (SEARCH_LENGTH*lineScalar -1)) !='\n')){
lineScalar++;
line = realloc(line, sizeof(char)*SEARCH_LENGTH*lineScalar);
assert(line);
fgets(line + SEARCH_LENGTH*(lineScalar - 1), SEARCH_LENGTH + 1, stream);
}// inner while
lineScalar = 1;
printf("Line:%s\n",line);
}
free(line);
free(word);
}
Thanks
You allocate SEARCH_LENGTH
characters in line
, but then immediately tell fgets()
that it's OK to read SEARCH_LENGTH+1
; if it does so, it will have corrupted the heap, giving you precisely the sort of error messages you're seeing. Don't let fgets()
write past the ends of your blocks!