Valgrind检测到琐碎代码的未列出的堆内存使用

Valgrind detects unfreed heap memory usage for a trivial code

本文关键字:未列出 内存 代码 检测 Valgrind      更新时间:2023-10-16

我的valgrind告诉我,它为最琐碎的C 代码找到了非填充的内存。

我的代码显示如下:

#include <iostream>
#include <string>
int main() {
std::cout << "Hello!!!!" << std::endl;
return 0;
}

,Valgrind的结果在这里:

==12455== HEAP SUMMARY:
==12455==     in use at exit: 72,704 bytes in 1 blocks
==12455==   total heap usage: 2 allocs, 1 frees, 73,728 bytes allocated
==12455== 
==12455== 72,704 bytes in 1 blocks are still reachable in loss record 1 of 1
==12455==    at 0x4C2DB8F: malloc (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==12455==    by 0x4EC3EFF: ??? (in /usr/lib/x86_64-linux-gnu/libstdc++.so.6.0.21)
==12455==    by 0x40106C9: call_init.part.0 (dl-init.c:72)
==12455==    by 0x40107DA: call_init (dl-init.c:30)
==12455==    by 0x40107DA: _dl_init (dl-init.c:120)
==12455==    by 0x4000C69: ??? (in /lib/x86_64-linux-gnu/ld-2.23.so)
==12455== 
==12455== LEAK SUMMARY:
==12455==    definitely lost: 0 bytes in 0 blocks
==12455==    indirectly lost: 0 bytes in 0 blocks
==12455==      possibly lost: 0 bytes in 0 blocks
==12455==    still reachable: 72,704 bytes in 1 blocks
==12455==         suppressed: 0 bytes in 0 blocks
==12455== 
==12455== For counts of detected and suppressed errors, rerun with: -v
==12455== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0)

这是Valgrind的错误?

这是由于C 标准库的工作方式。这些容器分配了大量内存(称为池(并在内部进行管理。他们基本上使用了自己的内存管理器,而不是依靠系统的内存管理器。因此,当对象被破坏时,它的内存将被内部分配器释放以重复使用,但没有回到操作系统。

这也在Valgrind的常见问题中描述。

要概括一些,valgrind是一个非常有用的工具,但您不应瞄准0泄漏,而是要理解其报告并找到表示代码中问题的泄漏。

我在ubuntu 19.04下使用valgrind 3.14.0,我没有得到任何检测。我用--leak-check=full跑了,没有。也许是Valgrind的一些版本。