本文簡要描述一下在Qt應用中使用VLD來檢測內存泄露。本次測試環境:QtCreator2.3 + Qt4.7.4-vs2008 + VS2008 Express.
1、下載並安裝:VLD-2.2: http://vld.codeplex.com/
鏈接:http://vld.codeplex.com/releases/70398/download/261406
假定安裝到c:/dev/vld-2.2目錄下。
2、創建測試項目:使用QtCreator創建一個Qt GUI項目。
修改.pro文件,添加如下內容:
win32 {
CONFIG(debug, debug|release) {
# DEFINES += _DEBUG
# vld 2.2 downloaded from http://vld.codeplex.com/
VLD_PATH = c:/dev/vld-2.2
INCLUDEPATH += $VLD_PATH/include
LIBS += -L$VLD_PATH/lib/Win32 -lvld
}
}
修改main.cpp文件,在main函數上面添加以下代碼:
#ifdef _DEBUG
#include "vld.h"
#endif
3、進行測試:
測試1:在MainWindow的構造函數中添加一行代碼:
new QWidget(this); // 不會泄露
編譯運行,在QtCreator的應用程序輸出窗口中將會有類似下面的內容:
Visual Leak Detector Version 2.2 installed.
Visual Leak Detector Version 2.2 installed.
No memory leaks detected.
Visual Leak Detector is now exiting.
以上表示沒有發現內存泄露。
(初次運行時可能無法運行,這是因爲找不到vld的dll文件。將C:\dev\vld-2.2\bin\Win32目錄下的內容拷貝到PATH環境變量中所列的某個目錄即可)
測試2:再添加一行代碼:
new QWidget(0); // 這個會泄露
再次編譯運行,結果爲:
Visual Leak Detector Version 2.2 installed.
WARNING: Visual Leak Detector detected memory leaks!
---------- Block 8 at 0x00EF14E0: 20 bytes ----------
Call Stack:
e:\works\test_vld_qt\mainwindow.cpp (18): test_vld_qt.exe!MainWindow::MainWindow + 0x7 bytes
e:\works\test_vld_qt\main.cpp (10): test_vld_qt.exe!main + 0xA bytes
e:\qt\4.7.4-vs2008\src\winmain\qtmain_win.cpp (131): test_vld_qt.exe!WinMain + 0x12 bytes
f:\dd\vctools\crt_bld\self_x86\crt\src\crtexe.c (578): test_vld_qt.exe!__tmainCRTStartup + 0x35 bytes
f:\dd\vctools\crt_bld\self_x86\crt\src\crtexe.c (403): test_vld_qt.exe!WinMainCRTStartup
0x7C817067 (File and line number not available): kernel32.dll!RegisterWaitForInputIdle + 0x49 bytes
Data:
8C 8A 40 00 F8 81 F1 00 68 8A 40 00 00 00 CD CD ..@..... h.@.....
B0 82 F1 00 ........ ........
Visual Leak Detector detected 1 memory leak (56 bytes).
Largest number used: 432 bytes.
Total allocations: 432 bytes.
Visual Leak Detector is now exiting.
這次檢測到了內存泄露。
小結:如上所示,使用vld檢測內存泄露很容易,美中不足的是隻能使用VC++編譯器。儘管如此,我們也可以用它來在Win32下檢測內存泄露,然後再使用其它編譯器在其它平臺上進行編譯發佈。