内存泄漏和检测方法

一、内存泄漏概念

  动态申请的内存(new、malloc等),没有进行释放处理;在程序持续运行过程中,占用的系统内存会越来越多。

二、泄漏检测方法

1.检测之valgrind

// 编译添加–g参数
//valgrind --leak-check=full --show-reachable=yes --trace-children=yes ./ttsTestMain 
valgrind --tool=memcheck ./ttsTestMain 执行结果: ==29653== ==29653== HEAP SUMMARY: ==29653== in use at exit: 6,621 bytes in 65 blocks ==29653== total heap usage: 179 allocs, 114 frees, 2,412,787 bytes allocated ==29653== ==29653== LEAK SUMMARY: ==29653== definitely lost: 0 bytes in 0 blocks ==29653== indirectly lost: 0 bytes in 0 blocks ==29653== possibly lost: 0 bytes in 0 blocks ==29653== still reachable: 6,621 bytes in 65 blocks ==29653== suppressed: 0 bytes in 0 blocks ==29653== Rerun with --leak-check=full to see details of leaked memory ==29653== ==29653== For counts of detected and suppressed errors, rerun with: -v ==29653== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0)

2.检测之tcmalloc

 

依赖库:libunwind-1.1  gperftools

通过 LD_PRELOAD 设置链接的堆栈处理库
通过 HEAPPROFILE 设置生成分析文件的位置

设置环境记录到文件:
env LD_PRELOAD="/home/app4/e2e_Tts/lib/tcmalloc/libtcmalloc.so" HEAPPROFILE="./perf_log/perf_leak.log" ./ttsTestMain

查看文件信息:
pprof --text /usr/bin/ls ./perf_log/perf_leak.log.0020.heap  # 读取 heap 转化成分析结果

直接打印:
env PPROF_PATH=./pprof HEAPCHECK=normal ./ttsTestMain

 


  • 首先终端输入export PPROF_PATH=/usr/local/bin/pprof
  • 将tcmalloc库链接到程序中,注意应该将tcmalloc库最后链接到程序中;
    • 如果直接使用gcc编译,则使用-ltcmalloc链接
    • 如果使用cmake,则在target_link_libraries中添加tcmalloc
  • 重新编译程序
  • 运行 env HEAPCHECK=normal 程序名 即可检查程序是否有内存泄露

 

3.检测之函数重载

C++环境下,我们通过new操作来申请内存,通过delete操作来释放内存,所以如果能够改写默认的new和delete操作的行为,就可以检测内存的状态。
参考:https://www.jianshu.com/p/060063f91f5e
问题:使用vector.pushback时core,待后续分析
====待补充

 

posted @ 2020-08-20 14:07  小菜77  阅读(1920)  评论(0编辑  收藏  举报