realloc() invalid old size

后端 未结 5 961
慢半拍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:46

    realloc call will re-allocate memory by taking a pointer to a storage area on the heap i.e a dynamically allocated memory result of a call to malloc.

    In your case the problem is that you are allocating memory on the stack and not dynamically by a call to malloc which results memory allocation on the heap. And, passing the pointer of the automatic character array line to _getline which uses it for call to realloc. So, you got the error.

    Try dynamically allocating the character array line :

    char* line  = (char *) malloc(MAXLINE); 
    char* longest = ( char *) malloc(MAXLINE);
    

提交回复
热议问题