Detecting C/C++ memory leaks with valgrind
整理一下我使用 valgrind 於 Linux/FreeBSD 偵測 C/C++ 程式裡的 memory leaks 的心得。
Tips for memory leak hunting for GCC/G++:
- First of all, use a version of valgrind that will work with current GNU C++ tools: the first that can do this is valgrind 1.0.4, but later versions should work at least as well.
- Second of all, use a completely unoptimized build to avoid confusing valgrind.
- Third, use GLIBCXX_FORCE_NEW to keep extraneous pool allocation noise from cluttering debug information.
- Fourth, it may be necessary to force deallocation in other libraries as well, namely the "C" library.
Suggested valgrind flags, given the suggestions above about setting up the runtime environment, library, and test file, might be:
valgrind --verbose \
--num-callers=20 \
--leak-check=yes \
--leak-resolution=high \
--show-reachable=yes \
a.out
《Tips for memory leak hunting》這邊有更詳盡的使用建議。將上述經驗包裝起來後,就成了 valgrind-run.sh 這支程式,寫成 script 以後就方便記憶 OS/Compiler 相依或其他重點設定的部份。
我另外寫了一支 valgrind-summarize.pl 程式,從複雜的 valgrind 輸出裡,擷取重要的資訊,以人類易讀的 key-value pairs 或機器易懂的 XML 格式輸出,方便後續(自動)使用。支援的欄位有:
leak_summary:definitely_lost:bytes leak_summary:definitely_lost:blocks leak_summary:possibly_lost:bytes leak_summary:possibly_lost:blocks leak_summary:still_reachable:bytes leak_summary:still_reachable:blocks leak_summary:suppressed:bytes leak_summary:suppressed:blocks leak_summary:unwanted_lost:bytes leak_summary:unwanted_lost:blocks
諸位可於 valgrind-run.sh on github 與 valgrind-summarize.pl on github 下載這兩支 scripts。



One Comment
有ARM 的版本嗎?感覺ARM的 support很不完整
Post a Comment