tar -xf valgrind-3.21.0.tar.bz2 cd valgrind-3.21.0
如果ubuntu在解压的时候出现如下报错
1 2 3 4 5
❯ tar -xf valgrind-3.21.0.tar.bz2 tar (child): lbzip2: Cannot exec: No such file or directory tar (child): Error is not recoverable: exiting now tar: Child returned status 2 tar: Error is not recoverable: exiting now
==24089== Memcheck, a memory error detector ==24089== Copyright (C) 2002-2022, and GNU GPL'd, by Julian Seward et al. ==24089== Using Valgrind-3.21.0 and LibVEX; rerun with -h for copyright info ==24089== Command: ./test ==24089== Parent PID: 24056 ==24089== ==24089== ==24089== HEAP SUMMARY: ==24089== in use at exit: 8 bytes in 2 blocks ==24089== total heap usage: 4 allocs, 2 frees, 72,716 bytes allocated ==24089== ==24089== 4 bytes in 1 blocks are definitely lost in loss record 1 of 2 ==24089== at 0x484880F: malloc (vg_replace_malloc.c:431) ==24089== by 0x1091F8: main (in /home/lyk/ub-vm/test) ==24089== ==24089== 4 bytes in 1 blocks are definitely lost in loss record 2 of 2 ==24089== at 0x484880F: malloc (vg_replace_malloc.c:431) ==24089== by 0x1091C1: test_leak() (in /home/lyk/ub-vm/test) ==24089== by 0x10922C: main (in /home/lyk/ub-vm/test) ==24089== ==24089== LEAK SUMMARY: ==24089== definitely lost: 8 bytes in 2 blocks ==24089== indirectly lost: 0 bytes in 0 blocks ==24089== possibly lost: 0 bytes in 0 blocks ==24089== still reachable: 0 bytes in 0 blocks ==24089== suppressed: 0 bytes in 0 blocks ==24089== ==24089== For lists of detected and suppressed errors, rerun with: -s ==24089== ERROR SUMMARY: 2 errors from 2 contexts (suppressed: 0 from 0)
在最后的summry里面可以看到,这里提示 definitely lost 了8个字节,而且是在两个不同的区块中丢失的。和我们的代码吻合。
如果你不调用 test_leak() 函数,那么就不会出现第二次的内存泄漏,报告会变成只有 4 bytes in 1 blocks ,因为valgrind是通过可执行文件来检测是否有内存泄漏的,他不会扫描你的代码(那样的成本太高了而且不一定准确!)