概述
Visual Leak Detector(VLD)是一款用于Visual C++的免费的内存泄露检测工具。他的特点有:可以得到内存泄漏点的调用堆栈,如果可以的话,还可以得到其所在文件及行号; 可以得到泄露内存的完整数据; 可以设置内存泄露报告的级别;并且是开源免费的。美中不足的是只能使用VC++编译器,关于linux的内存泄露,可以使用valgrind工具进行检测。
创建测试项目
使用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 #vld安装目录
INCLUDEPATH += $VLD_PATH/include
LIBS += -L$VLD_PATH/lib/Win32 -lvld
}
}
修改main.cpp文件,在main函数上面添加以下代码:
#ifdef _DEBUG
#include "vld.h"
#endif
进行测试:
测试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.ini 将内存泄漏信息写入文件
通过修改vld.ini文件(ReportFile选项),可将内存泄漏信息写入文件中,将源代码中的vld.ini文件拷贝到运行目录下,修改vld.ini文件中的选项参数,ReportFile = XXXX/XXX.txt,ReportTo =both(原始ReportTo = debugger),重新运行后,会生成报告文件;
注
VLD好像对中文路径不支持。
在Release下运行,VLD不起作用,