使用tcmalloc检测内存泄漏
2018-05-08 本文已影响790人
chnmagnus
安装
请自行搜索 google-perftools的安装。
使用tcmalloc检测内存泄露
在执行程序的时候,设置tcmalloc内存泄露检测的相关环境变量:
LD_PRELOAD="/usr/lib64/libtcmalloc.so" HEAPCHECK=normal ./bin/exe
如果该exe中有内存泄露的话,tcmalloc会打印一些相关信息,如果上面命令的输出如下:
Leak check _main_ detected leaks of 1136 bytes in 2 objects
The 2 largest leaks:
Leak of 568 bytes in 1 objects allocated from:
@ 7fa7f4197dd2
@ 7fa7f4198c30
@ 7fa7fd11f780
@ 7fa7fd15aaf3
@ 7fa7fd15189a
@ 7fa7fd1519e8
@ 7fa7fd151ac5
@ 7fa7fd151d9f
@ 7fa7fd15afd3
@ 7fa7fd1520ed
@ 7fa7fd11ea42
@ 7fa7f14dfb35
@ 7fa7fd11f151
@ 0
Leak of 568 bytes in 1 objects allocated from:
@ 7fa7f4197dd2
@ 7fa7f4198c30
@ 7fa7fd12402f
@ 7fa7fd15aaf3
@ 7fa7fd15189a
@ 7fa7fd1519e8
@ 7fa7fd151ac5
@ 7fa7fd151d9f
@ 7fa7fd15afd3
@ 7fa7fd1520ed
@ 7fa7fd11ea42
@ 7fa7f14dfb35
@ 7fa7fd11f151
@ 0
If the preceding stack traces are not enough to find the leaks, try running THIS shell command:
pprof ./bin/exe "/tmp/exe.7539._main_-end.heap" --inuse_objects --lines --heapcheck --edgefraction=1e-10 --nodefraction=1e-10 --gv
If you are still puzzled about why the leaks are there, try rerunning this program with HEAP_CHECK_TEST_POINTER_ALIGNMENT=1 and/or with HEAP_CHECK_MAX_POINTER_OFFSET=-1
If the leak report occurs in a small fraction of runs, try running with TCMALLOC_MAX_FREE_QUEUE_SIZE of few hundred MB or with TCMALLOC_RECLAIM_MEMORY=false, it mi
Exiting with error code (instead of crashing) because of whole-program memory leaks
然后我们按照tcmalloc的提示,执行pprof相关命令查看内存泄露的代码位置:
pprof ./bin/exe "/tmp/exe.7539._main_-end.heap" --inuse_objects --lines --heapcheck --edgefraction=1e-10 --nodefraction=1e-10 --text
该命令的输出为文本方式表示的。
使用doc输出内存泄露调用关系图
有的时候,内存泄露相关的调用关系比较复杂,这时候最好能生成调用关系图,方便排查内存泄露问题
- 生成dot文件
pprof ./bin/exe"/tmp/exe.7539._main_-end.heap" --inuse_objects --lines --heapcheck --edgefraction=1e-10 --nodefraction=1e-10 --dot > exe.dot
- 生成png格式的图片
dot -Tpng -o ./exe.png ./exe.dot
也可以通过参数调整输出其他格式的可视化结果。