2015-04-07 49 views
4

考慮以下代碼:Valgrind的報告太多mallocs

int main(int argc, char const *argv[]) 
{ 
    char *string = NULL; 
    string = malloc(sizeof(char) * 30); 
    free(string); 
    return 0; 
} 

我的malloc一個字符指針,那麼我以後釋放它。現在考慮valgrind輸出:

==58317== Memcheck, a memory error detector 
==58317== Copyright (C) 2002-2013, and GNU GPL'd, by Julian Seward et al. 
==58317== Using Valgrind-3.11.0.SVN and LibVEX; rerun with -h for copyright info 
==58317== Command: ./a.out 
==58317== 
==58317== 
==58317== HEAP SUMMARY: 
==58317==  in use at exit: 34,941 bytes in 424 blocks 
==58317== total heap usage: 505 allocs, 81 frees, 41,099 bytes allocated 
==58317== 
==58317== LEAK SUMMARY: 
==58317== definitely lost: 0 bytes in 0 blocks 
==58317== indirectly lost: 0 bytes in 0 blocks 
==58317==  possibly lost: 0 bytes in 0 blocks 
==58317== still reachable: 0 bytes in 0 blocks 
==58317==   suppressed: 34,941 bytes in 424 blocks 
==58317== 
==58317== For counts of detected and suppressed errors, rerun with: -v 
==58317== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0) 

怎麼可能有很多malloc和free?

編輯:這是我用valgrind --leak-check=yes --gen-suppressions=all ./a.out運行時得到的結果,我正在嘗試創建一個supp文件。

==60943== Memcheck, a memory error detector 
==60943== Copyright (C) 2002-2013, and GNU GPL'd, by Julian Seward et al. 
==60943== Using Valgrind-3.11.0.SVN and LibVEX; rerun with -h for copyright info 
==60943== Command: ./a.out 
==60943== 
==60943== 
==60943== HEAP SUMMARY: 
==60943==  in use at exit: 34,941 bytes in 424 blocks 
==60943== total heap usage: 505 allocs, 81 frees, 41,099 bytes allocated 
==60943== 
==60943== LEAK SUMMARY: 
==60943== definitely lost: 0 bytes in 0 blocks 
==60943== indirectly lost: 0 bytes in 0 blocks 
==60943==  possibly lost: 0 bytes in 0 blocks 
==60943== still reachable: 0 bytes in 0 blocks 
==60943==   suppressed: 34,941 bytes in 424 blocks 
==60943== 
==60943== For counts of detected and suppressed errors, rerun with: -v 
==60943== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 15 from 15) 
+0

我不能在這裏重現這一點 - 你確定你的a.out實際上是從上面的代碼構建的嗎? –

+2

隨着你的代碼,我得到了== == 14910 ==總堆使用率:1個分配,1個空閒,30個字節分配'你是什麼標題?你如何編譯二進制文件? –

+0

'gcc -g main.c'我確定我的a.out是從上面的代碼構建的。 – MortalMan

回答

6

通過鏈接到您的可執行文件的系統庫分配了這些塊(並且它們中的一些也被釋放)。

Valgrind的有一個默認suppression文件抑制系統庫泄漏,這是你可以在輸出進一步看到:

==58317==   suppressed: 34,941 bytes in 424 blocks 

如果您想正是被壓抑什麼更多的細節,你可以使用-v選項。

+0

那麼可以忽略這些嗎? – MortalMan

+0

@ user3711622:是的 - 他們通常是誤報,並且只有在系統庫中有時真正的泄漏難以解決。但我從來沒有見過它們。換句話說:如果他們被默認壓制,他們應該安全地忽略。 –

+0

如何從輸出中「隱藏」這些內容,以便我可以看到我造成的內存泄漏? – MortalMan