realloc() invalid old size

后端 未结 5 966
慢半拍i
慢半拍i 2021-02-09 00:09

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

5条回答
  •  梦毁少年i
    2021-02-09 00:49

    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.

提交回复
热议问题