整個測試代碼包含在main.cpp中,如下所示:爲什麼valgrind沒有在我的「測試」程序中檢測到內存泄漏?
#include <iostream>
using std::cout;
using std::endl;
void f(int i) {
int* pi = new int;
*pi = i;
std::cout << "*pi = " << *pi << std::endl;
}
int main(int argc, char *argv[]) {
int i = 0;
while (i < 10000) {
f(i);
++i;
}
return 0;
}
予編譯沒有優化-O0
(從一個Eclipse Qt工程)其中:
g++ -c -pipe -O0 -Wall -W -D_REENTRANT -DQT_NO_DEBUG -DQT_GUI_LIB -DQT_CORE_LIB -DQT_SHARED -I/usr/share/qt4/mkspecs/linux-g++ -I. -I/usr/include/qt4/QtCore -I/usr/include/qt4/QtGui -I/usr/include/qt4 -Irelease -o release/main.o main.cpp
然後作爲鏈接如下:
g++ -Wl,-O0 -o test release/main.o -L/usr/lib -lQtGui -lQtCore -lpthread
我的valgrind通過運行可執行文件,並得到下面的輸出:
laptop:~/workspace/test$ valgrind --leak-check=yes test
==3939== Memcheck, a memory error detector
==3939== Copyright (C) 2002-2009, and GNU GPL'd, by Julian Seward et al.
==3939== Using Valgrind-3.6.0.SVN-Debian and LibVEX; rerun with -h for copyright info
==3939== Command: test
==3939==
==3939==
==3939== HEAP SUMMARY:
==3939== in use at exit: 0 bytes in 0 blocks
==3939== total heap usage: 1,387 allocs, 1,387 frees, 64,394 bytes allocated
==3939==
==3939== All heap blocks were freed -- no leaks are possible
==3939==
==3939== For counts of detected and suppressed errors, rerun with: -v
==3939== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 13 from 8)
我相信Valgrind把報告內存泄漏,而不是沒有任何泄漏,因爲在呼叫分配給new int
編輯的堆內存是可能的:改變上面的代碼使用std ::法院,而不是qDebug ()具有相同的結果
如果我編譯和鏈接相同的代碼(從一個Eclipse CDT項目),沒有Qt的依賴,Valgrind的檢測泄漏:
g++ -O0 -g3 -Wall -c -fmessage-length=0 -MMD -MP -MF"main.d" -MT"main.d" -o"main.o" "../main.cpp"
g++ -o"test2" ./main.o
==4604== HEAP SUMMARY:
==4604== in use at exit: 40,000 bytes in 10,000 blocks
==4604== total heap usage: 10,000 allocs, 0 frees, 40,000 bytes allocated
==4604==
==4604== 40,000 bytes in 10,000 blocks are definitely lost in loss record 1 of 1
==4604== at 0x402569A: operator new(unsigned int) (vg_replace_malloc.c:255)
==4604== by 0x8048756: f(int) (main.cpp:7)
==4604== by 0x80487BB: main (main.cpp:18)
==4604==
==4604== LEAK SUMMARY:
==4604== definitely lost: 40,000 bytes in 10,000 blocks
==4604== indirectly lost: 0 bytes in 0 blocks
==4604== possibly lost: 0 bytes in 0 blocks
==4604== still reachable: 0 bytes in 0 blocks
==4604== suppressed: 0 bytes in 0 blocks
==4604==
==4604== For counts of detected and suppressed errors, rerun with: -v
==4604== ERROR SUMMARY: 1 errors from 1 contexts (suppressed: 19 from 8)
我ü唱Kubuntu 10.04 32位,並嘗試調試和發佈構建,我做錯了什麼或爲什麼valgrind報告與Qt鏈接時的內存泄漏?
但願這是編譯器消除了代碼,因爲它認爲沒有效果呢? – sharptooth 2011-01-24 08:43:22
@sharptooth:我不這麼認爲,因爲在調試模式下qDebug寫入標準輸出這是一個副作用,應該防止編譯器消除?我也嘗試過`std :: cout`而不是`qDebug`(這個調用在release中被刪除)並得到相同的結果。你和我有同樣的結果嗎? – 2011-01-24 08:51:40
我還沒有試過這段代碼。但對我來說,看起來應該報告泄漏,並且我可以假設它沒有報告的兩個原因 - 編譯器優化或堆干擾valgrind的特殊實現。 – sharptooth 2011-01-24 08:54:21