2013-10-10 24 views
2

在工作中,我用C編寫了一個相當複雜的軟件,我經常使用valgrind來測試它。到目前爲止,該程序完美地工作,沒有內存泄漏或數組邊界違規,並且在valgrind報告中,'frees'的數量與'malloc'的數量相匹配 - 非常好。令我感到困擾的是它報告了數千個釋放和malloc。而且我知道一個事實,我沒有超過50-60。我知道當我的程序調用'fopen'時,這個調用被valgrind計算到malloc的數量,同樣'fclose'被計算爲'frees'的數量。但在我的情況下,這仍然不能解釋我看到的內存被混合和釋放的次數。我仔細搜尋了代碼,尋找罪魁禍首,但我什麼都沒有。我不能在這裏發佈任何代碼,原因很明顯,但我只想知道,我錯過了什麼? valgrind是否還有其他C操作計入malloc和free的數量?valgrind將所有C操作都視爲「malloc」和「free」?

這是我的valgrind報告。正如你所看到的,從這個角度看,一切都很好。

Memcheck, a memory error detector 
Copyright (C) 2002-2012, and GNU GPL'd, by Julian Seward et al. 
Using Valgrind-3.8.1 and LibVEX; rerun with -h for copyright info 
Command: ./Codec 
Parent PID: 3526 

HEAP SUMMARY: 
    in use at exit: 0 bytes in 0 blocks 
    total heap usage: 2,407 allocs, 2,407 frees, 28,877,748 bytes allocated 

All heap blocks were freed -- no leaks are possible 

For counts of detected and suppressed errors, rerun with: -v 
ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 6 from 6) 
+3

對於(int i = 0; i!= 10000; ++ i){free(malloc(1)); }'? –

+5

如果您調用C庫例程或與任何庫鏈接並調用它們,它們可以調用malloc()和free()。 –

+0

你使用任何庫嗎?通常他們會在幕後分配和釋放內存 – Pankrates

回答

0

那麼,如果您調用庫函數執行malloc和免費調用,您將看到很多分配和釋放。一些庫函數,分配的系統調用是strdup,pthread_create,timer_create等

0

請記住,有很多函數調用可以分配內存,strdup,fopen,創建線程,加載共享對象,解析時區或語言環境信息(作爲時間相關的函數可能需要),3.d方庫可以以多種方式分配內存,等等。

但是,隨着Valgrind的地塊工具運行程序,http://valgrind.org/docs/manual/ms-manual.html(閱讀這些文檔)

例如

valgrind --depth=20 --tool=massif ./Calc 

這會產生一個massif.out.XXX文件,它顯示了各種分配來源以及堆的快照,例如,作爲摘錄:

snapshot=9 
#----------- 
time=137984 
mem_heap_B=640 
mem_heap_extra_B=40 
mem_stacks_B=0 
heap_tree=peak 
n2: 640 (heap allocation functions) malloc/new/new[], --alloc-fns, etc. 
n1: 352 0x4BFD095A: __fopen_internal (in /usr/lib/libc-2.17.so) 
    n1: 352 0x4BFD0A39: [email protected]@GLIBC_2.1 (in /usr/lib/libc-2.17.so) 
    n0: 352 0x8048784: main (tailq_example.c:63) 
n5: 288 0x8048580: add_block (tailq_example.c:20) 
    n0: 72 0x8048748: main (tailq_example.c:60) 
    n0: 72 0x804875C: main (tailq_example.c:61) 
    n0: 72 0x80487DC: main (tailq_example.c:72) 
    n0: 72 0x80487F0: main (tailq_example.c:73) 
    n0: 0 in 1 place, below massif's threshold (01.00%)