简体   繁体   English

使用malloc和fgetc的内存泄漏

[英]Memory leak with malloc and fgetc

I'm having some trouble reading a like from user using malloc and getchar. 我在使用malloc和getchar从用户读取赞时遇到了一些麻烦。 I get the result, however, I get memory leaks using valgrind. 我得到了结果,但是,我使用valgrind遇到了内存泄漏。 I am pretty clueless in this and have asked my classmates and mentors, but none seem to find out why. 我对此一无所知,并问过我的同学和导师,但似乎没人知道原因。

char *ReadLineFile(FILE *infile){
   int i=0;
   char c;
   char *newStringLine;
   newStringLine = (char *) malloc(sizeof(char));
   while( (c = fgetc(infile)) != '\n' ){
        newStringLine[i++] = c;
        realloc(newStringLine, (sizeof(char) * (i+1)));
   }
   newStringLine[i] = '\0';
   return newStringLine;
}

Valgrind gives me several errors, including Invalid write/read of 1, and invalid realloc. Valgrind给我一些错误,包括无效的1读/写和无效的重新分配。

Your usage of realloc() is erroneous. 您对realloc()是错误的。

realloc() , if successful, frees the passed pointer and returns a new pointer with the allocated memory. realloc()如果成功,则释放传递的指针,并返回带有分配的内存的新指针。 You need to 你需要

  • catch the return value of realloc() in a temporary pointer, 在一个临时指针中捕获realloc()的返回值,
  • check against NULL to ensure success and then 检查NULL以确保成功,然后

    • If returned pointer is not NULL, ie, reallocation is successful, use the new pointer. 如果返回的指针不是NULL,即重新分配成功,则使用新的指针。
    • If the returned pointer is NULL, make some decisions and you can keep using the old pointer (passed as argument). 如果返回的指针为NULL,请做出一些决定,您可以继续使用旧指针(作为参数传递)。

Related, quoting C11 , chapter §7.22.3.5 相关内容,引用C11 ,第§7.22.3.5章

The realloc function deallocates the old object pointed to by ptr and returns a pointer to a new object that has the size specified by size . realloc函数取消分配 ptr指向的旧对象并返回一个指向具有size指定size 的新对象的指针 [....] [....]

and, 和,

[...] If memory for the new object cannot be allocated, the old object is not deallocated and its value is unchanged. [...]如果无法分配用于新对象的内存,则不会释放旧对象,并且其值不变。

Otherwise, in case, realloc() is successful, you are ( most probably ) trying to use an already free-d memory, which , of course, causes undefined behavior . 否则,如果realloc()成功,则( 很可能 )您尝试使用已经释放的内存,这当然会导致未定义的行为


Uh-oh, and did I mention, please see this discussion on why not to cast the return value of malloc() and family in C ? 嗯,我刚才提到了, 请参阅有关为什么不在C中malloc()和family的返回值的讨论

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM