Valgrind是運行在Linux上一套基於仿真技術的程序調試和分析工具,是公認的最接近Purify的產品,它包含一個內核——一個軟件合成的CPU,和一系列的小工具,每個工具都可以完成一項任務——調試,分析,或測試等。Valgrind可以檢測內存泄漏和內存越界,還可以分析cache的使用等,靈活輕巧而又強大。
1.Valgrind概觀
Valgrind的最新版是3.2.3,該版本包含下列工具:
1)memcheck:檢查程序中的內存問題,如泄漏、越界、非法指針等。
2)callgrind:檢測程序代碼覆蓋,以及分析程序性能。
3)cachegrind:分析CPU的cache命中率、丟失率,用於進行代碼優化。
4)helgrind:用於檢查多線程程序的競態條件。
5)massif:堆棧分析器,指示程序中使用了多少堆內存等信息。
6)lackey:
7)nulgrind:
2.Valgrind工具詳解
2.1 Memcheck
最常用的工具,用來檢測程序中出現的內存問題,所有對內存的讀寫都會被檢測到,一切對malloc、free、new、delete的調用都會被捕獲。所以,它能檢測以下問題:
1)對未初始化內存的使用;
2)讀/寫釋放后的內存塊;
3)讀/寫超出malloc分配的內存塊;
4)讀/寫不適當的棧中內存塊;
5)內存泄漏,指向一塊內存的指針永遠丟失;
6)不正確的malloc/free或new/delete匹配;
7)memcpy()相關函數中的dst和src指針重疊。
這些問題往往是C/C++程序員最頭疼的問題,Memcheck能在這里幫上大忙。
2.2 Callgrind
和gprof類似的分析工具,但它對程序的運行觀察更是入微,能給我們提供更多的信息。和gprof不同,它不需要在編譯源代碼時附加特殊選項,但加上調試選項是推薦的。Callgrind收集程序運行時的一些數據,建立函數調用關系圖,還可以有選擇地進行cache模擬。在運行結束時,它會把分析數據寫入一個文件。callgrind_annotate可以把這個文件的內容轉化成可讀的形式。
說明:這個工具我也沒有用會,網上基本沒有找到有指導性的文檔,暫時留在后面慢慢研究吧。
2.3 Cachegrind
Cache分析器,它模擬CPU中的一級緩存I1,Dl和二級緩存,能夠精確地指出程序中cache的丟失和命中。如果需要,它還能夠為我們提供cache丟失次數,內存引用次數,以及每行代碼,每個函數,每個模塊,整個程序產生的指令數。這對優化程序有很大的幫助。作一下廣告:valgrind自身利用該工具在過去幾個月內使性能提高了25%-30%。據早先報道,kde的開發team也對valgrind在提高kde性能方面的幫助表示感謝。
2.4 Helgrind
它主要用來檢查多線程程序中出現的競爭問題。Helgrind尋找內存中被多個線程訪問,而又沒有一貫加鎖的區域,這些區域往往是線程之間失去同步的地方,而且會導致難以發掘的錯誤。Helgrind實現了名為“Eraser”的競爭檢測算法,並做了進一步改進,減少了報告錯誤的次數。不過,Helgrind仍然處於實驗階段。
2.5 Massif
堆棧分析器,它能測量程序在堆棧中使用了多少內存,告訴我們堆塊,堆管理塊和棧的大小。Massif能幫助我們減少內存的使用,在帶有虛擬內存的現代系統中,它還能夠加速我們程序的運行,減少程序停留在交換區中的幾率。Massif對內存的分配和釋放做profile。程序開發者通過它可以深入了解程序的內存使用行為,從而對內存使用進行優化。這個功能對C++尤其有用,因為C++有很多隱藏的內存分配和釋放。
此外,lackey和nulgrind也會提供。Lackey是小型工具,很少用到;Nulgrind只是為開發者展示如何創建一個工具。我們就不做介紹了。
3.使用Valgrind
Valgrind使用起來非常簡單,你甚至不需要重新編譯你的程序就可以用它。當然如果要達到最好的效果,獲得最准確的信息,還是需要按要求重新編譯一下的。比如在使用memcheck的時候,最好關閉優化選項。
valgrind命令的格式如下:
valgrind [valgrind-options] your-prog [your-prog options]
一些常用的選項如下:
選項 |
作用 |
-h --help |
顯示幫助信息。 |
--version |
顯示valgrind內核的版本,每個工具都有各自的版本。 |
-q --quiet |
安靜地運行,只打印錯誤信息。 |
-v --verbose |
打印更詳細的信息。 |
--tool=<toolname> [default: memcheck] |
最常用的選項。運行valgrind中名為toolname的工具。如果省略工具名,默認運行memcheck。 |
--db-attach=<yes|no> [default: no] |
綁定到調試器上,便於調試錯誤。 |
3.1 檢測內存泄漏
示例代碼如下:
1 #include <stdlib.h> 2 3 #include <stdio.h> 4 5 int main(void) 6 7 { 8 9 char *ptr; 10 11 ptr = (char *)malloc(10); 12 13 return 0; 14 15 }
保存為memleak.c並編譯,然后用valgrind檢測。
1 $ gcc -o memleak memleak.c
(valgrind和purify最大的不同在於:valgrind只接管程序執行的過程,編譯時不需要valgrind干預,而purify會干預程序編譯過程)
1 $ valgrind --tool=memcheck ./memleak
我們得到如下錯誤信息:
1 [konten@tencent test_valgrind]$ valgrind ./memleak 2 3 ==29646== Memcheck, a memory error detector. 4 5 ==29646== Copyright (C) 2002-2007, and GNU GPL'd, by Julian Seward et al. 6 7 ==29646== Using LibVEX rev 1732, a library for dynamic binary translation. 8 9 ==29646== Copyright (C) 2004-2007, and GNU GPL'd, by OpenWorks LLP. 10 11 ==29646== Using valgrind-3.2.3, a dynamic binary instrumentation framework. 12 13 ==29646== Copyright (C) 2000-2007, and GNU GPL'd, by Julian Seward et al. 14 15 ==29646== For more details, rerun with: -v 16 17 ==29646== 18 19 ==29646== 20 21 ==29646== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 15 from 1) 22 23 ==29646== malloc/free: in use at exit: 10 bytes in 1 blocks. //指示在程序退出時,還有多少內存沒有釋放。 24 25 ==29646== malloc/free: 1 allocs, 0 frees, 10 bytes allocated. // 指示該執行過程malloc和free調用的次數。 26 27 ==29646== For counts of detected errors, rerun with: -v // 提示如果要更詳細的信息,用-v選項。 28 29 ==29646== searching for pointers to 1 not-freed blocks. 30 31 ==29646== checked 56,164 bytes. 32 33 ==29646== 34 35 ==29646== LEAK SUMMARY: 36 37 ==29646== definitely lost: 10 bytes in 1 blocks. 38 39 ==29646== possibly lost: 0 bytes in 0 blocks. 40 41 ==29646== still reachable: 0 bytes in 0 blocks. 42 43 ==29646== suppressed: 0 bytes in 0 blocks. 44 45 ==29646== Rerun with --leak-check=full to see details of leaked memory. 46 47 [konten@tencent test_valgrind]$
以上結果中,紅色的是手工添加的說明信息,其他是valgrind的輸出。可以看到,如果我們僅僅用默認方式執行,valgrind只報告內存泄漏,但沒有顯示具體代碼中泄漏的地方。
因此我們需要使用 “--leak-check=full”選項啟動 valgrind,我們再執行一次:
1 [konten@tencent test_valgrind]$ valgrind --leak-check=full ./memleak 2 3 ==29661== Memcheck, a memory error detector. 4 5 ==29661== Copyright (C) 2002-2007, and GNU GPL'd, by Julian Seward et al. 6 7 ==29661== Using LibVEX rev 1732, a library for dynamic binary translation. 8 9 ==29661== Copyright (C) 2004-2007, and GNU GPL'd, by OpenWorks LLP. 10 11 ==29661== Using valgrind-3.2.3, a dynamic binary instrumentation framework. 12 13 ==29661== Copyright (C) 2000-2007, and GNU GPL'd, by Julian Seward et al. 14 15 ==29661== For more details, rerun with: -v 16 17 ==29661== 18 19 ==29661== 20 21 ==29661== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 15 from 1) 22 23 ==29661== malloc/free: in use at exit: 10 bytes in 1 blocks. 24 25 ==29661== malloc/free: 1 allocs, 0 frees, 10 bytes allocated. 26 27 ==29661== For counts of detected errors, rerun with: -v 28 29 ==29661== searching for pointers to 1 not-freed blocks. 30 31 ==29661== checked 56,164 bytes. 32 33 ==29661== 34 35 ==29661== 10 bytes in 1 blocks are definitely lost in loss record 1 of 1 36 37 ==29661== at 0x401A846: malloc (vg_replace_malloc.c:149) 38 39 ==29661== by 0x804835D: main (memleak.c:6) 40 41 ==29661== 42 43 ==29661== LEAK SUMMARY: 44 45 ==29661== definitely lost: 10 bytes in 1 blocks. 46 47 ==29661== possibly lost: 0 bytes in 0 blocks. 48 49 ==29661== still reachable: 0 bytes in 0 blocks. 50 51 ==29661== suppressed: 0 bytes in 0 blocks. 52 53 [konten@tencent test_valgrind]$
和上次的執行結果基本相同,只是多了上面藍色的部分,指明了代碼中出現泄漏的具體位置。
以上就是用valgrind檢查內存泄漏的方法,用到的例子比較簡單,復雜的代碼最后結果也都一樣。
3.2 其他內存問題
我們下面的例子中包括常見的幾類內存問題:堆中的內存越界、踩內存、棧中的內存越界、非法指針使用、重復free。
1 #include <stdlib.h> 2 #include <stdio.h> 3 int main(void) 4 { 5 char *ptr = malloc(10); 6 ptr[12] = 'a'; // 內存越界 7 8 memcpy(ptr +1, ptr, 5); // 踩內存 9 10 char a[10]; 11 a[12] = 'i'; // 數組越界 12 13 free(ptr); // 重復釋放 14 free(ptr); 15 char *p1; 16 *p1 = '1'; // 非法指針 17 18 return 0; 19 }
編譯:
1 gcc -o invalidptr invalidptr.c -g
執行:
1 valgrind --leak-check=full ./invalidptr
結果如下:
1 [konten@tencent test_valgrind]$ valgrind --leak-check=full ./invalidptr 2 3 ==29776== Memcheck, a memory error detector. 4 5 ==29776== Copyright (C) 2002-2007, and GNU GPL'd, by Julian Seward et al. 6 7 ==29776== Using LibVEX rev 1732, a library for dynamic binary translation. 8 9 ==29776== Copyright (C) 2004-2007, and GNU GPL'd, by OpenWorks LLP. 10 11 ==29776== Using valgrind-3.2.3, a dynamic binary instrumentation framework. 12 13 ==29776== Copyright (C) 2000-2007, and GNU GPL'd, by Julian Seward et al. 14 15 ==29776== For more details, rerun with: -v 16 17 ==29776== 18 19 ==29776== Invalid write of size 1 //堆內存越界被查出來 20 21 ==29776== at 0x80483D2: main (invalidptr.c:7) 22 23 ==29776== Address 0x4159034 is 2 bytes after a block of size 10 alloc'd 24 25 ==29776== at 0x401A846: malloc (vg_replace_malloc.c:149) 26 27 ==29776== by 0x80483C5: main (invalidptr.c:6) 28 29 ==29776== 30 31 ==29776== Source and destination overlap in memcpy(0x4159029, 0x4159028, 5) //踩內存 32 33 ==29776== at 0x401C96D: memcpy (mc_replace_strmem.c:116) 34 35 ==29776== by 0x80483E6: main (invalidptr.c:9) 36 37 ==29776== 38 39 ==29776== Invalid free() / delete / delete[] //重復釋放 40 41 ==29776== at 0x401B3FB: free (vg_replace_malloc.c:233) 42 43 ==29776== by 0x8048406: main (invalidptr.c:16) 44 45 ==29776== Address 0x4159028 is 0 bytes inside a block of size 10 free'd 46 47 ==29776== at 0x401B3FB: free (vg_replace_malloc.c:233) 48 49 ==29776== by 0x80483F8: main (invalidptr.c:15) 50 51 ==29776== 52 53 ==29776== Use of uninitialised value of size 4 54 55 ==29776== at 0x804840D: main (invalidptr.c:19) 56 57 ==29776== //非法指針,導致coredump 58 59 ==29776== Process terminating with default action of signal 11 (SIGSEGV): dumping core 60 61 ==29776== Bad permissions for mapped region at address 0x80482AD 62 63 ==29776== at 0x804840D: main (invalidptr.c:19) 64 65 ==29776== 66 67 ==29776== ERROR SUMMARY: 4 errors from 4 contexts (suppressed: 15 from 1) 68 69 ==29776== malloc/free: in use at exit: 0 bytes in 0 blocks. 70 71 ==29776== malloc/free: 1 allocs, 2 frees, 10 bytes allocated. 72 73 ==29776== For counts of detected errors, rerun with: -v 74 75 ==29776== All heap blocks were freed -- no leaks are possible. 76 77 Segmentation fault 78 79 [konten@tencent test_valgrind]$
從上面的結果看出,除了棧內存越界外,其他常見的內存問題都可以用valgrind簡單的查出來。
3.3 顯示代碼覆蓋
用callgrind工具能方便的顯示程序執行的代碼覆蓋情況。
看如下例子:
3.4 顯示線程競態條件 <該版本暫不支持>
用helgrind工具可以在多線程代碼中找到可能產生競態條件的地方。
4.memcheck 工具的常用選型
4.1 leak-check
--leak-check=<no|summary|yes|full> [default: summary]
用於控制內存泄漏檢測力度。
no
,不檢測內存泄漏;
summary
,僅報告總共泄漏的數量,不報告具體泄漏位置;
yes/full
,報告泄漏總數、泄漏的具體位置
4.2 show-reachable
--show-reachable=<yes|no> [default: no]
用於控制是否檢測控制范圍之外的泄漏,比如全局指針、static指針等。
1 #include <stdlib.h> 2 #include <stdio.h> 3 //char *gptr = NULL; 4 5 int main(void) 6 { 7 gptr = (char *)malloc(10); 8 9 return 0; 10 }
對應以上代碼,若--show-reachable為no,則valgrind不報告內存泄漏,否則會報告。
4.3 undef-value-errors
--undef-value-errors=<yes|no> [default: yes]
用於控制是否檢測代碼中使用未初始化變量的情況。
對應以下代碼:
1 int a; 2 printf("a = %d \n", a);
若 --undef-value-errors=no,則valgrind不報告錯誤,否則報告“Use of uninitialised value ...”的錯誤。
4.4 其他選項
1 --log-file=filename 將結果輸出到文件。 2 --log-socket=192.168.0.1:12345 輸出到網絡。 3 --trace-children=<yes|no> [default: no] 4 --track-fds=<yes|no> [default: no] 5 --log-fd=<number> [default: 2, stderr] 6 --xml=<yes|no> [default: no] 7 --num-callers=<number> [default: 12] 8 --show-below-main=<yes|no> [default: no]
5.Valgrind的編譯安裝
5.1 下載源代碼
下載地址http://valgrind.org/downloads/current.html#current ,截止目前為止,最新版本是3.2.3
5.2 編譯
編譯,在源代碼目錄下執行:
1 ./configure --prefix=[你自己的安裝目錄] 2 make;make install
便好了。
5.3 配置缺省選項
valgrind提供3種方式用於設置缺省選項:
a、~/.valgrindrc
文件;
b
、環境變量$VALGRIND_OPTS;
c
、當前目錄下的.valgrindrc文件;
優先順序為 a、b、c
.valgrindrc
的格式為:
1 --ToolName:OptionName=OptionVal
如:
1 --memcheck:leak-check=yes 2 --memcheck:show-reachable=yes