请问有人能解释一下为什么Valgrind将这个程序分类为“Definitely Lost: 2 bytes in 1 block”内存泄漏吗?我知道注释掉的那行代码可以解决问题,但是我不理解这种分类。根据Valgrind文档,这个内存泄漏应该被分类为“间接可达”。我也很好奇为什么这被认为是内存泄漏,并且希望得到解释。尽管程序在main
函数结束时终止,手动释放所有内容是否是一个好习惯呢?
#include <stdlib.h>
struct wrapper {
char *data;
};
char *strdup(const char *);
struct wrapper *walloc(struct wrapper *root)
{
if (root == NULL){
root = (struct wrapper *) malloc(sizeof(struct wrapper));
root->data = strdup("H");
}
return root;
}
int main(){
struct wrapper *root;
root = NULL;
root = walloc(root);
//free(root->data);
return 0;
}
以下是Valgrind的输出:
$ valgrind --leak-check=full ./leak
==26489== Memcheck, a memory error detector
==26489== Copyright (C) 2002-2013, and GNU GPL'd, by Julian Seward et al.
==26489== Using Valgrind-3.10.0 and LibVEX; rerun with -h for copyright info
==26489== Command: ./leak
==26489==
==26489==
==26489== HEAP SUMMARY:
==26489== in use at exit: 2 bytes in 1 blocks
==26489== total heap usage: 2 allocs, 1 frees, 1,790 bytes allocated
==26489==
==26489== 2 bytes in 1 blocks are definitely lost in loss record 1 of 1
==26489== at 0x4C29F90: malloc (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==26489== by 0x4EB79C9: strdup (in /usr/lib/libc-2.20.so)
==26489== by 0x400542: walloc (leak.c:13)
==26489== by 0x400542: main (leak.c:23)
==26489==
==26489== LEAK SUMMARY:
==26489== definitely lost: 2 bytes in 1 blocks
==26489== indirectly lost: 0 bytes in 0 blocks
==26489== possibly lost: 0 bytes in 0 blocks
==26489== still reachable: 0 bytes in 0 blocks
==26489== suppressed: 0 bytes in 0 blocks
==26489==
==26489== For counts of detected and suppressed errors, rerun with: -v
==26489== ERROR SUMMARY: 1 errors from 1 contexts (suppressed: 0 from 0)
free()
可以暴露程序中难以找到的错误。始终在分配代码完成后直接实现释放是一个好习惯。 - Lundinroot
)和2个字节的间接丢失(root->data
)。你能发布来自valgrind的完整输出吗? - Bill Lynch#include <string.h>
,因为编译器可以对strdup
进行一些“神奇”的操作(有时候GCC会这样做)。 - Basile Starynkevitch-O3
编译的吗? - Bill LynchCFLAGS = -Wall -O3 -pg
。如果我不使用它进行编译,我会得到不同的输出——直接8字节和间接2字节。我现在知道问题出在哪里了。 - Pan Thomakos