Valgrind是运行在Linux上一套基于仿真技术的程序调试和分析工具,是公认的最接近Purify的产品,它包含一个内核——一个软件合成的CPU,和一系列的小工具,每个工具都可以完成一项任务——调试,分析,或测试等。Valgrind可以检测内存泄漏和内存越界,还可以分析cache的使用等,灵活轻巧而又强大。
一 Valgrind概观
Valgrind的最新版是3.2.3,该版本包含下列工具:
1、memcheck:检查程序中的内存问题,如泄漏、越界、非法指针等。
2、callgrind:检测程序代码覆盖,以及分析程序性能。
3、cachegrind:分析CPU的cache命中率、丢失率,用于进行代码优化。
4、helgrind:用于检查多线程程序的竞态条件。
5、massif:堆栈分析器,指示程序中使用了多少堆内存等信息。
6、lackey
7、nulgrind
二 Valgrind工具详解
1.Memcheck
最常用的工具,用来检测程序中出现的内存问题,所有对内存的读写都会被检测到,一切对malloc、free、new、delete的调用都会被捕获。所以,它能检测以下问题:
1、对未初始化内存的使用;
2、读/写释放后的内存块;
3、读/写超出malloc分配的内存块;
4、读/写不适当的栈中内存块;
5、内存泄漏,指向一块内存的指针永远丢失;
6、不正确的malloc/free或new/delete匹配;
7、memcpy()相关函数中的dst和src指针重叠。
这些问题往往是C/C++程序员最头疼的问题,Memcheck能在这里帮上大忙。
2.Callgrind
用callgrind工具能方便的显示程序执行的代码覆盖情况。 和gprof类似的分析工具,但它对程序的运行观察更是入微,能给我们提供更多的信息。和gprof不同,它不需要在编译源代码时附加特殊选项,但加上调试选项是推荐的。Callgrind收集程序运行时的一些数据,建立函数调用关系图,还可以有选择地进行cache模拟。在运行结束时,它会把分析数据写入一个文件。callgrind_annotate可以把这个文件的内容转化成可读的形式。
3.Cachegrind
Cache分析器,它模拟CPU中的一级缓存I1,Dl和二级缓存,能够精确地指出程序中cache的丢失和命中。如果需要,它还能够为我们提供cache丢失次数,内存引用次数,以及每行代码,每个函数,每个模块,整个程序产生的指令数。这对优化程序有很大的帮助。
作一下广告:valgrind自身利用该工具在过去几个月内使性能提高了25%-30%。据早先报道,kde的开发team也对valgrind在提高kde性能方面的帮助表示感谢。
4.Helgrind
它主要用来检查多线程程序中出现的竞争问题。Helgrind寻找内存中被多个线程访问,而又没有一贯加锁的区域,这些区域往往是线程之间失去同步的地方,而且会导致难以发掘的错误。Helgrind实现了名为“Eraser”的竞争检测算法,并做了进一步改进,减少了报告错误的次数。不过,Helgrind仍然处于实验阶段。
5. Massif
堆栈分析器,它能测量程序在堆栈中使用了多少内存,告诉我们堆块,堆管理块和栈的大小。Massif能帮助我们减少内存的使用,在带有虚拟内存的现代系统中,它还能够加速我们程序的运行,减少程序停留在交换区中的几率。
Massif对内存的分配和释放做profile。程序开发者通过它可以深入了解程序的内存使用行为,从而对内存使用进行优化。这个功能对C++尤其有用,因为C++有很多隐藏的内存分配和释放
此外,lackey和nulgrind也会提供。Lackey是小型工具,很少用到;Nulgrind只是为开发者展示如何创建一个工具。我们就不做介绍了。
三 使用Valgrind
安装:
从官网http://www.valgrind.org下载最新版本
#tar xvf valgrind-3.11.1.tar.bz2
#cd valgrind-3.11.1
#./configure --prefix=/usr/local/valgrind--指定安装目录
#make
#make install
1、检测内存泄漏
示例代码如下:
#include <stdio.h>
#include <stdlib.h>
char* getMemory()
{
char *p = (char *)malloc(30);
return p;
}
int main()
{
char *p = getMemory();
p = NULL;
return 0;
}
保存为memleak.c并编译,然后用valgrind检测。
$ gcc -o memleak memleak.c -g
(valgrind和purify最大的不同在于:valgrind只接管程序执行的过程,编译时不需要valgrind干预,而purify会干预程序编译过程)
valgrind --tool=memcheck --leak-check=full --show-reachable=yes ./memleak
参数说明:
--leak-check=full
no: 不进行内存泄露检测; summary: 显示内存泄露情况; full:不仅显示内存泄露,还显示出错代码。
--show-reachable=yes
详细显示still reachable 和 indirectly lost两种类型的内存泄露,默认不显示
我们得到如下错误信息:
[root@xxx ~/valgrind-3.8.1/bin]# valgrind --tool=memcheck --leak-check=full --show-reachable=yes ./memleak
==20448== Memcheck, a memory error detector
==20448== Copyright (C) 2002-2012, and GNU GPL'd, by Julian Seward et al.
==20448== Using Valgrind-3.8.1 and LibVEX; rerun with -h for copyright info
==20448== Command: ./memleak
==20448==
==20448==
==20448== HEAP SUMMARY:
==20448== in use at exit: 30 bytes in 1 blocks
==20448== total heap usage: 1 allocs, 0 frees, 30 bytes allocated
==20448==
==20448== 30 bytes in 1 blocks are definitely lost in loss record 1 of 1
==20448== at 0x4C278FE: malloc (vg_replace_malloc.c:270)
==20448== by 0x4005B5: getMemory() (test.cpp:5) //指明了代码中泄漏的具体位置
==20448== by 0x4005CC: main (test.cpp:11)
==20448==
==20448== LEAK SUMMARY:
==20448== definitely lost: 30 bytes in 1 blocks
==20448== indirectly lost: 0 bytes in 0 blocks
==20448== possibly lost: 0 bytes in 0 blocks
==20448== still reachable: 0 bytes in 0 blocks
==20448== suppressed: 0 bytes in 0 blocks
==20448==
==20448== For counts of detected and suppressed errors, rerun with: -v
==20448== ERROR SUMMARY: 1 errors from 1 contexts (suppressed: 6 from 6)
[root@xxx ~/valgrind-3.8.1/bin]#
泄露类型种类:
possibly lost: 指针指向内存的内部位置。
still reachable: 程序运行结束后,虽然没有被释放,但仍然可以访问。
definitely lost: 内存无法被访问。
indirectly lost: 虽然有地址指向该空间,但已经无法被访问了。
2、其他内存问题
我们下面的例子中包括常见的几类内存问题:堆中的内存越界、踩内存、栈中的内存越界、非法指针使用、重复free。
#include <stdlib.h>
#include <stdio.h>
int main(void)
{
char *ptr = malloc(10);
ptr[12] = 'a'; // 内存越界
memcpy(ptr +1, ptr, 5); // 踩内存
char a[10];
a[12] = 'i'; // 数组越界
free(ptr); // 重复释放
free(ptr);
char *p1;
*p1 = '1'; // 非法指针
return 0;
}
编译: gcc -o invalidptr invalidptr.c -g
执行:valgrind --leak-check=full ./invalidptr
结果如下:
$ valgrind --leak-check=full ./invalidptr
==29776== Memcheck, a memory error detector.
==29776== Copyright (C) 2002-2007, and GNU GPL'd, by Julian Seward et al.
==29776== Using LibVEX rev 1732, a library for dynamic binary translation.
==29776== Copyright (C) 2004-2007, and GNU GPL'd, by OpenWorks LLP.
==29776== Using valgrind-3.2.3, a dynamic binary instrumentation framework.
==29776== Copyright (C) 2000-2007, and GNU GPL'd, by Julian Seward et al.
==29776== For more details, rerun with: -v
==29776==
==29776== Invalid write of size 1 //堆内存越界被查出来
==29776== at 0x80483D2: main (invalidptr.c:6)
==29776== Address 0x4159034 is 2 bytes after a block of size 10 alloc'd
==29776== at 0x401A846: malloc (vg_replace_malloc.c:149)
==29776== by 0x80483C5: main (invalidptr.c:5)
==29776==
==29776== Source and destination overlap in memcpy(0x4159029, 0x4159028, 5) //踩内存
==29776== at 0x401C96D: memcpy (mc_replace_strmem.c:116)
==29776== by 0x80483E6: main (invalidptr.c:7)
==29776==
==29776== Invalid free() / delete / delete[] //重复释放
==29776== at 0x401B3FB: free (vg_replace_malloc.c:233)
==29776== by 0x8048406: main (invalidptr.c:11)
==29776== Address 0x4159028 is 0 bytes inside a block of size 10 free'd
==29776== at 0x401B3FB: free (vg_replace_malloc.c:233)
==29776== by 0x80483F8: main (invalidptr.c:10)
==29776==
==29776== Use of uninitialised value of size 4
==29776== at 0x804840D: main (invalidptr.c:13)
==29776== //非法指针,导致coredump
==29776== Process terminating with default action of signal 11 (SIGSEGV): dumping core
==29776== Bad permissions for mapped region at address 0x80482AD
==29776== at 0x804840D: main (invalidptr.c:13)
==29776==
==29776== ERROR SUMMARY: 4 errors from 4 contexts (suppressed: 15 from 1)
==29776== malloc/free: in use at exit: 0 bytes in 0 blocks.
==29776== malloc/free: 1 allocs, 2 frees, 10 bytes allocated.
==29776== For counts of detected errors, rerun with: -v
==29776== All heap blocks were freed -- no leaks are possible.
Segmentation fault