《Linux C/C++ Memory Leak Detection Tool》
1. 內存使用情況分析
1.1 系統總內存分析
通過cat /proc/meminfo,可用的物理內存=MemFree+Buffers+Cached。
| MemTotal: 5933132 kB |
echo 3 > /proc/sys/vm/drop_caches,會清理系統的cache。
Writing to this will cause the kernel to drop clean caches, dentries and inodes from memory, causing that memory to become free.
1-to free pagecache, 2-to free dentries and inodes, 3-to free pagecache, dentries and inodes。
1.2 進程內存分析
cat /proc/{pid}/maps
2 內存泄露
2.1 內存泄露類型
1. 常發性內存泄漏
發生內存泄漏的代碼會被多次執行到,每次被執行的時候都會導致一塊內存泄漏
2. 偶發性內存泄漏
發生內存泄漏的代碼只有在某些特定環境或操作過程下才會發生。常發性和偶發性是相對的。對於特定的環境,偶發性的也許就變成了常發性的。所以測試環境和測試方法對檢測內存泄漏至關重要
3. 一次性內存泄漏
發生內存泄漏的代碼只會被執行一次,或者由於算法上的缺陷,導致總會有一塊且僅有一塊內存發生泄漏
4. 隱式內存泄漏
程序在運行過程中不停的分配內存,但是直到結束的時候才釋放內存。嚴格的說這里並沒有發生內存泄漏,因為最終程序釋放了所有申請的內存。但是對於一個服務器程序,需要運行幾天,幾周甚至幾個月,不及時釋放內存也可能導致最終耗盡系統的所有內存。所以,我們稱這類內存泄漏為隱式內存泄漏
2.2 常用內存泄露檢測工具
C/C++ 1. Valgrind: Debugging and profiling Linux programs, aiming at programs written in C and C++ 2. ccmalloc: Linux和Solaris下對C和C++程序的簡單的使用內存泄漏和malloc調試庫 3. LeakTracer: Linux、Solaris和HP-UX下跟蹤和分析C++程序中的內存泄漏 4. Electric Fence: Linux分發版中由Bruce Perens編寫的malloc()調試庫 5. Leaky: Linux下檢測內存泄漏的程序 6. Dmalloc: Debug Malloc Library 7. MEMWATCH: 由Johan Lindh編寫,是一個開放源代碼C語言內存錯誤檢測工具,主要是通過gcc的precessor來進行 8. KCachegrind: A visualization tool for the profiling data generated by Cachegrind and Calltree
2.3 內存檢測原理
3. 常用工具
3.1 Linux內核內存泄漏檢測kmemleak
kmemlean提供了一種檢測內核內存泄露的方法,當內存對象沒有被釋放是,將其記錄在/sys/kernel/debug/kmemleak中。
3.1.1 使能kmemleak
CONFIG_DEBUG_KMEMLEAK=y CONFIG_DEBUG_KMEMLEAK_EARLY_LOG_SIZE=400 # CONFIG_DEBUG_KMEMLEAK_TEST is not set CONFIG_DEBUG_KMEMLEAK_DEFAULT_OFF=n----------默認打開
如果沒有打開KMEMLEAK_FULL,則使用了精簡版。完整版比較耗內存,精簡版適合嵌入式調試。
3.1.2 配置獲取kmemleak結果
參數配置:
off 禁用kmemleak(不可逆) stack=on 啟用任務堆棧掃描(default) stack=off 禁用任務堆棧掃描 scan=on 啟動自動記憶掃描線程(default) scan=off 停止自動記憶掃描線程 scan=<secs> 設置n秒內自動記憶掃描 scan 開啟內核掃描 clear 清除內存泄露報告 dump=<addr> 轉存信息對象在<addr> 通過“kmemleak = OFF”,也可以在啟動時禁用Kmemleak在內核命令行。在初始化kmemleak之前,內存的分配或釋放這些動作被存儲在一個前期日志緩沖區。這個緩沖區的大小通過配CONFIG_DEBUG_KMEMLEAK_EARLY_LOG_SIZE設置。
cat /sys/kernel/debug/kmemleak > kmemleak.txt
3.1.3 分析kmemleak泄漏情況
參考文檔:
《Linux Kernel Memory Leak Detection》
3.2 valgrind
Linux C/C++ Memory Leak Detection Tool
Linux 下幾款程序內存泄漏檢查工具
https://events.linuxfoundation.org/images/stories/pdf/lceu11_marinas.pdf
http://blog.thewebsitepeople.org/2011/03/linux-memory-leak-detection/
https://serverfault.com/questions/257759/something-eats-all-memory-i-suspect-memory-leak-on-some-app-how-to-detect-wha
