Qt 專案要查內存洩露,Visual Leak Detector(VLD)是最省事的入門選擇。本次測試環境為 QtCreator 2.3、Qt 4.7.4-vs2008 搭配 VS2008 Express。
從 https://vld.codeplex.com/ 下載 VLD 2.2,假定裝在 c:/dev/vld-2.2。要留意 codeproject.com 上那個早期版本太老、偵測不準,別用。
win32 {
CONFIG(debug, debug|release) {
# vld 2.2 downloaded from https://vld.codeplex.com/
VLD_PATH = c:/dev/vld-2.2
INCLUDEPATH += $VLD_PATH/include
LIBS += -L$VLD_PATH/lib/Win32 -lvld
}
}
#ifdef _DEBUG #include "vld.h" #endif
測試一:在 MainWindow 建構子裡寫 new QWidget(this);。有指定父物件,Qt 的父子機制會替你回收,輸出OMO:
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 中的任一目錄即可。
測試二:改成 new QWidget(0);,沒有父物件也沒人 delete,這次就被抓到:
WARNING: Visual Leak Detector detected memory leaks!
---------- Block 8 at 0x00EF14E0: 20 bytes ----------
Call Stack:
mainwindow.cpp (18): MainWindow::MainWindow + 0x7 bytes
main.cpp (10): main + 0xA bytes
...
Visual Leak Detector detected 1 memory leak (56 bytes).
Largest number used: 432 bytes.
Total allocations: 432 bytes.
它不只告訴洩漏多少位元組,還附上完整的呼叫堆疊與檔案行號,定位起來非常直接。
接入成本極低,缺點是只能搭配 VC++ 編譯器。即便如此,在 Win32 階段先用它把洩露清乾淨,再用其他編譯器在其他平台編譯發布,是很划算的流程安排。