1. 下载代码
www.valgrind.org/
2. 安装
tar jxf *.tar.bz2
make
sudo make install
ubuntu 上要安装 sudo apt-get install libc6-dbg 才行
3. 内存泄露诊断
编写代码 Virt.cpp
#include <unistd.h>
#include <stdio.h>
int main()
{
for(int i=0;i<50;i++)
{
int *p = new int[1024];
printf("time is: %d \n",i);
sleep(1);
}
return 0;
}
编译: g++ -g Virt.cpp -o Virt.exe
运行 valgrind --tool=memcheck --leak-check=full ./Virt.exe
得到:
time is: 47
time is: 48
time is: 49
==15429==
==15429== HEAP SUMMARY:
==15429== in use at exit: 204,800 bytes in 50 blocks
==15429== total heap usage: 50 allocs, 0 frees, 204,800 bytes allocated
==15429==
==15429== 204,800 bytes in 50 blocks are definitely lost in loss record 1 of 1
==15429== at 0x40271A9: operator new[](unsigned int) (vg_replace_malloc.c:343)
==15429== by 0x80484D2: main (Virt.cpp:7)
==15429==
==15429== LEAK SUMMARY:
==15429== definitely lost: 204,800 bytes in 50 blocks
==15429== indirectly lost: 0 bytes in 0 blocks
==15429== possibly lost: 0 bytes in 0 blocks
==15429== still reachable: 0 bytes in 0 blocks
==15429== suppressed: 0 bytes in 0 blocks
==15429==
==15429== For counts of detected and suppressed errors, rerun with: -v
==15429== ERROR SUMMARY: 1 errors from 1 contexts (suppressed: 17 from 6)
4. 内存越界诊断