拥有此代码:
#include <stdlib.h>
#include <stdio.h>
void main()
{
char *line = calloc(1024, 1);
size_t size = 0;
getline(&line, &size, stdin);
free(line);
}
瓦尔格林抱怨道:
==5931== HEAP SUMMARY:
==5931== in use at exit: 1,024 bytes in 1 blocks
==5931== total heap usage: 3 allocs, 2 frees, 2,168 bytes allocated
==5931==
==5931== 1,024 bytes in 1 blocks are definitely lost in loss record 1 of 1
==5931== at 0x4837B65: calloc (vg_replace_malloc.c:752)
==5931== by 0x10916B: main (test.c:5)
==5931==
==5931== LEAK SUMMARY:
==5931== definitely lost: 1,024 bytes in 1 blocks
我看过其他相关帖子,但找不到这个特殊案例的答案:/
最佳答案
这是一个glibc错误(或长期存在的glibc行为,取决于您如何看待它):
getdelim leaks line when n is zero
在glibc中很难修复,因为许多应用程序假设当长度为零时不必初始化行指针,如klutt的original reply中所述。如果glibc开始释放或在零长度情况下使用行指针,这将导致崩溃。
关于c - Valgrind报告从stdin的getline之后释放的指针发生内存泄漏,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/58670205/