I am doing an exercise for fun from KandR C programming book. The program is for finding the longest line from a set of lines entered by the user and then prints it.
Her
You get an invalid old size
error when your code writes the memory that malloc
/realloc
allocated for "housekeeping information". This is where they store the "old" allocated size. This also happens when the pointer that you pass to realloc
has not been properly initialized, i.e. it's neither a NULL
nor a pointer previously returned from malloc
/calloc
/realloc
.
In your case, the pointer passed to realloc
is actually an array allocated in automatic memory - i.e. it's not a valid pointer. To fix, change the declarations of line
and longest
as follows:
char *line = malloc(MAXLINE), *longest = malloc(MAXLINE);
To avoid memory leaks, make sure that you call free(line)
and free(longest)
at the end of your program.