对于C,C++这类语言开发的程序,内存泄露后果很严重,为了第一时间避免这种问题的发生,集成内存检测工具到单元测试里显得非常重要。
内存泄漏的分析工具,目前比较经典的有valgrind和gperftools,而gperftools安装简单,易于集成到单元测试中,且对运行速度的影响也比较小。
gperftools是google开发的一款非常实用的工具集,主要包括:性能优异的malloc free内存分配器tcmalloc;基于tcmalloc的堆内存检测和内存泄漏分析工具heap-profiler,heap-checker,使用heap-checker来检测内存泄露。检测的方式有两种,一种是需要把tcmalloc库链接进工程,另一种不需要链接进工程,只需要在运行时通过LD_PRELOAD命令加载tcmalloc库。官方推荐第一种方法,第二种方式存在安全问题。
2.Gperftool集成到单元测试
2.1.安装
gperftools安装包
首先在跑单元测试的环境上安装gperftools,gperftools中包含了tcmalloc和pprof,这两个都是内存泄露检测和查看所需要的。在linux下,其安装步骤如下:
ltar xzvf gperftools-2.1.tar.gz
lcd gperftools-2.1
l./configure--enable-frame-pointers
lmake
lmake install
这里需要注意一点,在linux下,如果直接./configure,那么make时会报出编译错误:error Cannot calculate stack trace: will need to write for your environment。解决方法如上所示,在configure时加入选项--enable-frame-pointers。
安装之后就可以ls查看到/usr/local/lib/libtcmalloc*下有很多tcmalloc相关的库。另外pprof命令已经生效,具体位置为/usr/local/bin/pprof。
2.2.修改makefile
l设置环境变量
exportHEAPCHECK=normal,可以设置值:normal/strict/draconian,一般设置为normal。
export PPROF_PATH=/usr/local/bin/pprof
l增加编译连接-ltcmalloc
如下
注意这里在制作时出现了
在这篇文章里给出了解决办法:
【已解决】error : while loading shared libraries: libtcmalloc.so.4: cannot open shared object file_weixin_46353422的博客-CSDN博客
对于简单文件 test.cpp :
#include<iostream>#include<string>using namespace std;int main(){ cout<<"ysey!"<<endl;char * a = new char[100];return 0;}
进行如下操作:
可看出有一处泄露。
使用 pprof ./abc "/tmp/abc.74762._main_-end.heap" --inuse_objects --lines --heapcheck --edgefraction=1e-10 --nodefraction=1e-10 --text 可查看具体原因