一般檢查memory leak的工具不外乎如electric fence, leak tracer…等,但大部份的工具在使用上都很麻煩,必需重編你的程式並連結這些debug工具的library,開什麼玩笑,為了這樣我還要改Makefile…!@#$神經病

最近發現了一個小巧且功能還不算太簡陋,又很適合懶人使用的memory leak工具,它就是valgrind.在詳細說明它的功能前,先講一下它的使用方法,保證連鍵盤都懶得打的宅男都很愛用

只要在command line下指令: valgrind –leak-check=yes [your program]
Valgrind就會在runtime檢查你程式所有使用的記憶體,有些情況如上車不補票,或上車補錯票,它都可以幫你找出來..(不要跟我說不上車也不補票,很無聊耶,都這麼晚了,還不趕快回病院報到)

當然啦,我們要找個範例開刀啦…小弟不才,借用官網的程式說明一下debug訊息
由註解可以很容易看出問題點有兩個
(1)寫的範圍超過記憶體的區塊位址
(2)沒有呼叫free釋放malloc要求的記憶體

void f(void) 
{ 
int* x = malloc(10 * sizeof(int));
x[10] = 0; // problem 1: heap block overrun
// problem 2: memory leak -- x not freed
} 
 
int main(void) 
{ 
f();
return 0;
}

執行valgrind後發現得到如下分析的結果

省略部份版權宣告


下面的很清楚的說明了,在函式f發生了記憶體寫入超過alloc的記憶體範圍
==6968== Invalid write of size 4
==6968==    at 0x80483F4: f (in /root/test/lm)
==6968==    by 0x804841C: main (in /root/test/lm)
==6968==  Address 0x4156050 is 0 bytes after a block of size 40 alloc’d
==6968==    at 0x401B7E9: malloc (vg_replace_malloc.c:207)
==6968==    by 0x80483E7: f (in /root/test/lm)
==6968==    by 0x804841C: main (in /root/test/lm)
==6968==


結論報告中,明白的表示在函式f中,有malloc 40 bytes,但確沒有free掉,並在leak summary中確切寫出definitely lost:40 bytes in 1 block
==6968== ERROR SUMMARY: 1 errors from 1 contexts (suppressed: 11 from 1)
==6968== malloc/free: in use at exit: 40 bytes in 1 blocks.
==6968== malloc/free: 1 allocs, 0 frees, 40 bytes allocated.
==6968== For counts of detected errors, rerun with: -v
==6968== searching for pointers to 1 not-freed blocks.
==6968== checked 57,912 bytes.
==6968==
==6968==
==6968== 40 bytes in 1 blocks are definitely lost in loss record 1 of 1
==6968==    at 0x401B7E9: malloc (vg_replace_malloc.c:207)
==6968==    by 0x80483E7: f (in /root/test/lm)
==6968==    by 0x804841C: main (in /root/test/lm)
==6968==
==6968== LEAK SUMMARY:
==6968==    definitely lost: 40 bytes in 1 blocks.
==6968==      possibly lost: 0 bytes in 0 blocks.
==6968==    still reachable: 0 bytes in 0 blocks.
==6968==         suppressed: 0 bytes in 0 blocks.

以上就是文字模式的顯示訊息,當然啦,它還有GUI的輔助程式valkyrie可以幫助使用者更明瞭整個output的結果
講到valkyrie這個名字,很可能玩SC(StarCraft)的玩家會很熱血,沒錯,就是人類的正義女神號,雖然是個雞肋兵種,但名字還取得蠻好聽的
Valkyrie的畫面如下,我覺得valkyrie產生出來的結果跟文字模式是差不多的…

說到這邊你是否有點心動了呢?valgrind安裝的方式很簡單,去官網下載原始碼後,輸入
Configure
Make
Make install
就可以開始玩囉….

最後修改日期: 3 6 月, 2022

作者

留言

撰寫回覆或留言

發佈留言必須填寫的電子郵件地址不會公開。