c++没有垃圾回收机制,程序往往会出现内存泄露,即从堆上获取资源(malloc/new)、用完后没有返回(free/delete)给系统。
valgrind是一个检测内存泄露的工具。
安装
sudo apt-get install valgrind
使用
写一个产生内存泄露的代码,名为leak1.cpp
//leak1.cpp
#include <cstdlib>
using namespace std;
int main()
{
char* p = (char*)malloc(4);
//no free
return 0;
}
编译、输出名为leak的可执行程序:
g++ -g leak.cpp -o leak1
注意这里需要使用debug模式,即加-g
,否则一会儿valgrind没法输出错误的地方。
然后就是valgrind:
valgrind --tool=memcheck --leak-check=yes ./leak1
这里valgrind的参数有:--tool=memcheck
和--leak-check=yes
,而./leak1
是我的可执行程序。
输出类似如下:
==15133== Memcheck, a memory error detector
==15133== Copyright (C) 2002-2015, and GNU GPL'd, by Julian Seward et al.
==15133== Using Valgrind-3.11.0 and LibVEX; rerun with -h for copyright info
==15133== Command: ./leak
==15133==
==15133==
==15133== HEAP SUMMARY:
==15133== in use at exit: 4 bytes in 1 blocks
==15133== total heap usage: 1 allocs, 0 frees, 4 bytes allocated
==15133==
==15133== 4 bytes in 1 blocks are definitely lost in loss record 1 of 1
==15133== at 0x4C2DB8F: malloc (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==15133== by 0x400537: main (leak.cpp:4)
==15133==
==15133== LEAK SUMMARY:
==15133== definitely lost: 4 bytes in 1 blocks
==15133== indirectly lost: 0 bytes in 0 blocks
==15133== possibly lost: 0 bytes in 0 blocks
==15133== still reachable: 0 bytes in 0 blocks
==15133== suppressed: 0 bytes in 0 blocks
==15133==
==15133== For counts of detected and suppressed errors, rerun with: -v
==15133== ERROR SUMMARY: 1 errors from 1 contexts (suppressed: 0 from 0)
可以看到内存泄露发生在源码的第4行。