【发布时间】:2021-08-06 17:32:38
【问题描述】:
这是我的一段代码(目的是读取行并从中构建结构):
typedef struct{
size_t length;
char *letters;
}line;
static line ReadLine(){
char *buffor = NULL;
size_t length = 0;
int nRead = 0;
nRead = getline(&buffor, &length, stdin);
return nRead == -1 ? (line) {.length = 0, .letters = NULL} : (line) {.length = nRead, .letters = buffor};
}
稍后在我的 main 函数中,我释放了由 getline 函数分配的缓冲区:
void ReadFile(){
line l = ReadLine();
printLine(l);
free(l.letters);
}
但我知道有一些内存(使用 valgrind):Leak_StillReachable by malloc,其中函数 getline 是。
【问题讨论】:
-
你如何“得到”有一些内存没有被释放?有什么工具能告诉你吗?它说什么?显示该工具的确切输出。或者你是从你的程序的行为中推断出来的。什么行为?编辑问题以提供minimal reproducible example。
-
我使用了 valgrind(edited initial post),并且在函数 getline() 所在的同一行中得到了 Leak_StillReachable。
-
我已经用 valgrind 测试了你的代码:“所有堆块都被释放了——不可能有泄漏”。如果出现这种情况,您能否提供
printLine函数? -
它不会以任何方式修改缓冲区,只是使用 printf 函数打印它。虽然我使用的是 Clion valgring,但这可能是个问题?
-
那我猜是你本地的 libc
getline实现有问题(见this question as example)
标签: c memory memory-management memory-leaks valgrind