Valgrind
什么是valgrind
Valgrind是一套linux下GPL(开源)调试工具集合。
包括以下工具:
- memcheck
- callgrind
- cachegrind
- helgrind
- massif
memcheck
内存检查器
主要检查:
- use of uninitialised memory
- reading/writing memory after it has been freed
- reading/writing off the end of malloced blocks
- reading/writing inaoorioriate areas on the stack
- memory leaks
- mismatched use of malloc/new/free/delete
callgrind
收集运行数据、函数调用关系等
cachegrind
模拟L1和L2高速缓存
提供cache命中率、内存引用次数、程序指令数
helgrind
检查多线程竞争问题
massif
堆、栈分析器
如何安装?
linux下直接使用命令
sudo apt install valgrind
windows下
那我不管
怎么使用
通用命令
valgrind --tool=toolname args-val program args
其中–tool
用于选取tool
args-val
用于单词运行特殊需求。通过valgrand -h
进行查看
program
指定检测程序的对象
要求:编译时使用-g
参数、关闭编译优化
-h
help-version
-q
quiet work-v
verbose,更详细的信息-trace-children=no|yes
跟踪子线程-log-file-exactly=<file>
log文件
log 输出指令:-xml=yes
(仅memcheck可用)
memcheck
-leak-check=no|summary|full
要求对leak给出详细信息?
最常用:valgrind --tool=memcheck --leak-check=full --show-leak-kinds=all ./a.out
使用ctrl+c
结束
Memcheck将内存泄露分为两种,一种是可能的内存泄露(Possibly lost),另外一种是确定的内存泄露(Definitely lost)
Possibly lost 是指仍然存在某个指针能够访问某块内存,但该指针指向的已经不是该内存首地址
Definitely lost又分为两种:直接的(direct)和间接的(indirect)
直接和间接的区别就是,直接是没有任何指针指向该内存,间接是指指向该内存的指针都位于内存泄露处
至于其他工具,我觉得以我的水平用不到的
测试
测试以下代码
#include <stdio.h>
#include <stdlib.h>
int main()