Qt应用中检测内存泄露——VLD

来源:互联网 发布:游戏多核优化的多吗 编辑:程序博客网 时间:2024/06/11 16:36

本文简要描述一下在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目录下。

注:vld最初发表在codeproject.com,这个版本太老了。检测不准,不能使用。

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下检测内存泄露,然后再使用其它编译器在其它平台上进行编译发布。


原创粉丝点击