下载地址:https://www.valgrind.org/downloads/current.html
x86平台:./configure --prefix=<安装目录> ,make ,make install
arm平台:./configure --prefix=<安装目录> CC=<工具链> AR=<工具链> --host=<运行平台>, make make install
在x86平台编译时遇到问题:
解决方法:进入/usr/include目录,创建asm-generic目录的软链接asm,重新编译即可。
valgrind工具功能强大,自己当前主要用来检查内存泄漏的问题。用到的工具就是memcheck,这个也是默认的工具。在使用时通过--leak-check=full来指定。比如:
valgrind --leak-check=full --trace-children= yes ./a.out
常用参数如下:
--leak-check=full:指检查泄漏的地方,并展示详细信息,即具体申请内存的位置(编译时需要带-g参数);
--trace-children=yes:指也会进入子进程检查。
--log-file=filename:指定log输出文件,终端上将不会出现检查结果信息
--show-reachable=yes:打印出可能会导致内存泄漏的指针。这个申请的内存指针还没有沦为野指针,但是如果后面不释放的话(成为野指针),就会导致内存泄漏。
注意:在编译程序时使用-g参数,推荐使用-O0参数,优化级别越高,valgrind定位越不准确。
正常执行结束的程序,会在程序执行结束后看到统计结果。
有时程序会在后台一直运行,此时需要kill掉程序才会出现统计结果。此时可以通过vgdb参数,在程序运行过程中进行阶段性统计结果展示。
valgrind --leak-check=full --vgdb=yes --vgdb-error=0 ./a.out
--vgdb=yes:启用gdbsever,可以通过gdb来控制程序。
--vgdb-error=[number]:与--vgdb搭配使用,当达到[number]条错误消息后,会发送到gdb端。一般填0。
然后在新的终端中运行 gdb ./a.out
>> target remote | vgdb
>>continue (程序开始运行)
>> monitor leak_check full reachable any (使用ctrl+c终端运行,然后执行该命令)
此时就会将到目前为止出现的问题统计结果打印出来。
The details are in the Memcheck section of the user manual.
In short:
- "definitely lost" means your program is leaking memory -- fix those leaks!
- "indirectly lost" means your program is leaking memory in a pointer-based structure. (E.g. if the root node of a binary tree is "definitely lost", all the children will be "indirectly lost".) If you fix the "definitely lost" leaks, the "indirectly lost" leaks should go away.
- "possibly lost" means your program is leaking memory, unless you’re doing unusual things with pointers that could cause them to point into the middle of an allocated block; see the user manual for some possible causes. Use --show-possibly-lost=no if you don’t want to see these reports.
- "still reachable" means your program is probably ok -- it didn’t free some memory it could have. This is quite common and often reasonable. Don’t use --show-reachable=yes if you don’t want to see these reports.
- "suppressed" means that a leak error has been suppressed. There are some suppressions in the default suppression files. You can ignore suppressed errors.
definitely lost: 确定是有内存泄漏了,需要及时修复。
indirectly lost: 间接泄漏,如果含有指针的结构体产生内存泄漏时。
possibly lost: 可能产生的泄漏,直接操作指针,通过指针偏移的方式来访问内存时。
still reachable: 任然可以访问的内存指针,但是如果后面不释放的话,可能会造成泄漏。
suppressed: 内存泄漏已经被解决,可以忽略。
参考:
valgrind_manual.pdf(安装目录下share/doc目录有)