一、內存泄漏概念
動態申請的內存(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,待后續分析
====待補充