歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Qt應用中檢測內存洩露——VLD

Qt應用中檢測內存洩露——VLD

日期:2017/3/1 10:40:49   编辑:Linux編程

本文簡要描述一下在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文件,添加如下內容:

  1. win32 {
  2. CONFIG(debug, debug|release) {
  3. # DEFINES += _DEBUG
  4. # vld 2.2 downloaded from http://vld.codeplex.com/
  5. VLD_PATH = c:/dev/vld-2.2
  6. INCLUDEPATH += $VLD_PATH/include
  7. LIBS += -L$VLD_PATH/lib/Win32 -lvld
  8. }
  9. }

修改main.cpp文件,在main函數上面添加以下代碼:

  1. #ifdef _DEBUG
  2. #include "vld.h"
  3. #endif

3、進行測試:

測試1:在MainWindow的構造函數中添加一行代碼:

  1. new QWidget(this); // 不會洩露
編譯運行,在QtCreator的應用程序輸出窗口中將會有類似下面的內容:
  1. Visual Leak Detector Version 2.2 installed.
  2. Visual Leak Detector Version 2.2 installed.
  3. No memory leaks detected.
  4. Visual Leak Detector is now exiting.
以上表示沒有發現內存洩露。

(初次運行時可能無法運行,這是因為找不到vld的dll文件。將C:\dev\vld-2.2\bin\Win32目錄下的內容拷貝到PATH環境變量中所列的某個目錄即可)

測試2:再添加一行代碼:

  1. new QWidget(0); // 這個會洩露
再次編譯運行,結果為:
  1. Visual Leak Detector Version 2.2 installed.
  2. WARNING: Visual Leak Detector detected memory leaks!
  3. ---------- Block 8 at 0x00EF14E0: 20 bytes ----------
  4. Call Stack:
  5. e:\works\test_vld_qt\mainwindow.cpp (18): test_vld_qt.exe!MainWindow::MainWindow + 0x7 bytes
  6. e:\works\test_vld_qt\main.cpp (10): test_vld_qt.exe!main + 0xA bytes
  7. e:\qt\4.7.4-vs2008\src\winmain\qtmain_win.cpp (131): test_vld_qt.exe!WinMain + 0x12 bytes
  8. f:\dd\vctools\crt_bld\self_x86\crt\src\crtexe.c (578): test_vld_qt.exe!__tmainCRTStartup + 0x35 bytes
  9. f:\dd\vctools\crt_bld\self_x86\crt\src\crtexe.c (403): test_vld_qt.exe!WinMainCRTStartup
  10. 0x7C817067 (File and line number not available): kernel32.dll!RegisterWaitForInputIdle + 0x49 bytes
  11. Data:
  12. 8C 8A 40 00 F8 81 F1 00 68 8A 40 00 00 00 CD CD ..@..... h.@.....
  13. B0 82 F1 00 ........ ........
  14. Visual Leak Detector detected 1 memory leak (56 bytes).
  15. Largest number used: 432 bytes.
  16. Total allocations: 432 bytes.
  17. Visual Leak Detector is now exiting.
這次檢測到了內存洩露。


小結:如上所示,使用vld檢測內存洩露很容易,美中不足的是只能使用VC++編譯器。盡管如此,我們也可以用它來在Win32下檢測內存洩露,然後再使用其它編譯器在其它平台上進行編譯發布。

Copyright © Linux教程網 All Rights Reserved