valgrind使用
1.前置条件
Compile your program with -g to include debugginginformation so that Memcheck's error messages include exact linenumbers. Using-O0 is also a goodidea, if you can tolerate the slowdown. With-O1 line numbers in error messages canbe inaccurate, although generally speaking running Memcheck on code compiledat-O1 works fairly well, and the speed improvementcompared to running-O0 is quite significant.Use of-O2 and above is not recommended asMemcheck occasionally reports uninitialised-value errors which don'treally exist.
使用valgrind检测的程序,在编译时候,需要加上 -g。尽量使用 -O0不进行代码编译优化。
2.检测内存泄漏:
1)编译程序:
用 -g 选项增加debug信息, -O0 或者 -O1 均可,-O0 运行非常缓慢,-O1 行号和错误信息会不准确。
不要使用-O2 或者更高的优化级别。
2)运行,检测是否有内存泄漏:
valgrind --leak-check=yes myprog arg1 arg2
用以下命令可以查看具体是哪个调用堆栈产生了内存泄漏(但运行速度缓慢):
valgrind --leak-check=full --show-leak-kinds=all myprog arg1 arg2
valgrind --leak-check=yes myprog arg1 arg2
valgrind --leak-check=full --log-file=valgrind.log -v --track-origins=yes myprog arg1 arg2
堆栈不够大时加上--num-callers2:检测变量未赋初值--track-origins=yes