[英]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 你需要
realloc()
in a temporary pointer, realloc()
的返回值, check against NULL to ensure success and then 检查NULL以确保成功,然后
Related, quoting C11
, chapter §7.22.3.5 相关内容,引用
C11
,第§7.22.3.5章
The
realloc
function deallocates the old object pointed to byptr
and returns a pointer to a new object that has the size specified bysize
.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.