realloc() invalid old size

后端 未结 5 960
慢半拍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条回答
  •  太阳男子
    2021-02-09 00:43

    You are trying to realloc() memory that was not allocated dynamically with malloc(). You cannot do that.

    Also, if realloc() fails, the original memory is still allocated, and thus still needs to be freed with free(). So do not assign the return value of realloc() to the original pointer unless it is not NULL, otherwise you are leaking the original memory. Assign the return value of realloc() to a temp variable first, check its value, and then assign to the original pointer only if realloc() was successful.

提交回复
热议问题