Valgrind是一个提供程序调试及性能分析的工具集。其包含的工具主要有Memcheck,Cachegrind,Callgrind,Massif等。其中,最为常用的是Memcheck,其主要用来检查程序heap上的内存使用情况。本文档主要介绍Memcheck的用法和一些使用技巧。
其官方网站是:http://valgrind.org/
Valgrind主要用来检查程序中可能出现的以下问题:
其功能约束如下:
若有root权限,其安装方式如下:
若没有root权限,则在第3步时,可以用--prefix指定安装的目录
./configure–prefix=/home/work/yangfenqiang/
以下步骤相同。
编写程序test.cpp如下:
1 #include <iostream>
2 using namespace std;
3
4 int main()
5 {
6 int *a = new int[10];
7 a[11] = 0;
8 cout << a[11]<< endl;
9 return 0;
10 }
11
编译该程序:gcc–g–o test test.cpp
注意加入-g参数,便于valgrind读入符号表之类的信息以提供更丰富的错误定位信息。不推荐加入-O等优化参数,因为优化后的代码易于让valgrind解释错误。
运行“valgrind --tool=memcheck --leak-check=yes --show-reachable=yes test”,显示如下信息:
==2051== Memcheck, a memory error detector.
==2051== Copyright (C) 2002-2007, and GNU GPL'd, by Julian Seward et al.
==2051== Using LibVEX rev 1804, a library for dynamic binary translation.
==2051== Copyright (C) 2004-2007, and GNU GPL'd, by OpenWorks LLP.
==2051== Using valgrind-3.3.0, a dynamic binary instrumentation framework.
==2051== Copyright (C) 2000-2007, and GNU GPL'd, by Julian Seward et al.
==2051== For more details, rerun with: -v
==2051==
==2051== Invalid write of size 4
==2051== at 0x4009C6: main (test.cpp:7)
==2051== Address 0x4a2005c is 4 bytes after a block of size 40 alloc'd
==2051== at 0x490581B: operator new[](unsigned long) (vg_replace_malloc.c:274)
==2051== by 0x4009B9: main (test.cpp:6)
==2051==
==2051== Invalid read of size 4
==2051== at 0x4009D4: main (test.cpp:8)
==2051== Address 0x4a2005c is 4 bytes after a block of size 40 alloc'd
==2051== at 0x490581B: operator new[](unsigned long) (vg_replace_malloc.c:274)
==2051== by 0x4009B9: main (test.cpp:6)
0
==2051==
==2051== ERROR SUMMARY: 2 errors from 2 contexts (suppressed: 9 from 4)
==2051== malloc/free: in use at exit: 40 bytes in 1 blocks.
==2051== malloc/free: 1 allocs, 0 frees, 40 bytes allocated.
==2051== For counts of detected errors, rerun with: -v
==2051== searching for pointers to 1 not-freed blocks.
==2051== checked 198,560 bytes.
==2051==
==2051==
==2051== 40 bytes in 1 blocks are definitely lost in loss record 1 of 1
==2051== at 0x490581B: operator new[](unsigned long) (vg_replace_malloc.c:274)
==2051== by 0x4009B9: main (test.cpp:6)
==2051==
==2051== LEAK SUMMARY:
==2051== definitely lost: 40 bytes in 1 blocks.
==2051== possibly lost: 0 bytes in 0 blocks.
==2051== still reachable: 0 bytes in 0 blocks.
==2051== suppressed: 0 bytes in 0 blocks.
其中:
说明test.cpp的第7行发生内存访问越界,越界的位移为4。
在LEAK SUMMARY中:
--tool参数指明所要使用valgrind的哪一个工具,默认的为memcheck。因为大多数情况下我们只会用到memcheck工具,因此该参数可以不写。
在退出时检查是否有泄漏。Summary只是告诉我们有多少次泄漏,yes或full会告诉我们每次泄漏的详细信息。
通过设定该参数为yes,则显示still reachable类型的内存泄漏信息。
其他更多的运行参数信息可以查看《valgrind使用指南》及《valgrind manual》。