2011-12-18 23 views
5

看起來奇怪:只是一個循環,33個泄漏

$> cat main.c 
#include <stdio.h> 
int main(int ac, char **av) { 
    for (int i = 0; i < ac; i++) 
     printf("%s\n", av[i]); 
    return 0; 
} 
$> gcc main.c -std=c99 
$> valgrind ./a.out hello my friends 

這裏是結果:

==725== Memcheck, a memory error detector 
==725== Copyright (C) 2002-2011, and GNU GPL'd, by Julian Seward et al. 
==725== Using Valgrind-3.7.0 and LibVEX; rerun with -h for copyright info 
==725== Command: ./a.out hello my friends 
==725== 
--725-- ./a.out: 
--725-- dSYM directory is missing; consider using --dsymutil=yes 
./a.out 
hello 
my 
friends 
==725== 
==725== HEAP SUMMARY: 
==725==  in use at exit: 6,146 bytes in 33 blocks 
==725== total heap usage: 33 allocs, 0 frees, 6,146 bytes allocated 
==725== 
==725== LEAK SUMMARY: 
==725== definitely lost: 0 bytes in 0 blocks 
==725== indirectly lost: 0 bytes in 0 blocks 
==725==  possibly lost: 0 bytes in 0 blocks 
==725== still reachable: 6,146 bytes in 33 blocks 
==725==   suppressed: 0 bytes in 0 blocks 
==725== Rerun with --leak-check=full to see details of leaked memory 
==725== 
==725== For counts of detected and suppressed errors, rerun with: -v 
==725== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 1 from 1) 

如果有人知道爲什麼,可能請解釋一下這些泄漏來自哪裏,我會很感激!

祝你有美好的一天:-)

+0

用'--leak-check = full'重新運行。您可能會看到,分配是由您的環境完成的系統工作(一次性啓動/初始化事情),這些並非真正的泄漏。 – Mat 2011-12-18 09:34:44

+1

您是否按照valgrind輸出消息的建議「重新運行--leak-check = full以查看泄漏內存的詳細信息」? – bobbymcr 2011-12-18 09:34:51

回答

9

這些都不是泄漏。列爲still reachable的對象不應該麻煩你。如果你在上面的行中有一個非零值,那麼它應該會響起一個警鐘!

列出爲still reachable的33個塊最有可能是您的標準庫調用printf內部的一些塊。沒有什麼可擔心的。

考慮也看看this answer到類似的問題。

+0

完美。感謝您的回答:-) – DCMaxxx 2011-12-18 11:26:52

3

"still reachable"程序終止時真的沒有什麼可擔心的。

"still reachable"表示分配的內存尚未釋放,但仍有指向此內存的指針。因此valgrind不會將其標記爲真正的內存「泄漏」。

花費時間往往是浪費時間:在應用程序結束之前分配的內存,分配的內存將無論如何返回到操作系統,因爲應用程序正在終止。

+0

根據我的經驗,嘗試在運行結束時正確釋放所有對象非常重要。我發現了很多錯誤。確實,所謂的「泄漏」的嚴重性是微乎其微的,但它所施加的正確性的行爲具有廣泛的再執行。在大型項目上,它可以帶來真正的變化。它實際上是在我工作的兩個大項目(C的500K和150K行)上進行的。 – 2011-12-18 11:33:54