How to detect memory leaks in QtCreator on Windows?

23,526

Solution 1

After many tries I finally found a method to detect the memory leaks of a Qt project on Windows:

1) First, it cannot be done directly in Qt Creator so you need to create a Visual C++ project to do the memory leak detection. Thankfully, qmake makes this easy. Open the Qt SDK command line tool and run:

qmake -spec win32-msvc2008 -tp vc

This will convert your project to a .vcproj.

2) Open this project and add the necessary code for memory leak detection:

To your main.cpp file:

// Necessary includes and defines for memory leak detection:
#ifdef _MSC_VER
#define _CRTDBG_MAP_ALLOC
#include <crtdbg.h>
#endif // _MSC_VER


#if defined(_MSC_VER)

// Code to display the memory leak report
// We use a custom report hook to filter out Qt's own memory leaks
// Credit to Andreas Schmidts - http://www.schmidt-web-berlin.de/winfig/blog/?p=154

_CRT_REPORT_HOOK prevHook;

int customReportHook(int /* reportType */, char* message, int* /* returnValue */) {
  // This function is called several times for each memory leak.
  // Each time a part of the error message is supplied.
  // This holds number of subsequent detail messages after
  // a leak was reported
  const int numFollowupDebugMsgParts = 2;
  static bool ignoreMessage = false;
  static int debugMsgPartsCount = 0;

  // check if the memory leak reporting starts
  if ((strncmp(message,"Detected memory leaks!\n", 10) == 0)
    || ignoreMessage)
  {
    // check if the memory leak reporting ends
    if (strncmp(message,"Object dump complete.\n", 10) == 0)
    {
      _CrtSetReportHook(prevHook);
      ignoreMessage = false;
    } else
      ignoreMessage = true;

    // something from our own code?
    if(strstr(message, ".cpp") == NULL)
    {
      if(debugMsgPartsCount++ < numFollowupDebugMsgParts)
        // give it back to _CrtDbgReport() to be printed to the console
        return FALSE;
      else
        return TRUE;  // ignore it
    } else
    {
      debugMsgPartsCount = 0;
      // give it back to _CrtDbgReport() to be printed to the console
      return FALSE;
    }
  } else
    // give it back to _CrtDbgReport() to be printed to the console
    return FALSE;
}

#endif



int main(int argc, char *argv[]) {
    #if defined(_MSC_VER)
    _CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF);
    prevHook = _CrtSetReportHook(customReportHook);
    // _CrtSetBreakAlloc(157); // Use this line to break at the nth memory allocation
    #endif

    QApplication* app = new QApplication(argc, argv);   
    int appError = app->exec();
    delete app;

    #if defined(_MSC_VER)
    // Once the app has finished running and has been deleted,
    // we run this command to view the memory leaks:
    _CrtDumpMemoryLeaks();
    #endif 

    return appError;
}

3) With this, your project should now be able to detect memory leaks. Note the _MSC_VER defines so that this code is only executed when your run it from Visual C++ (not from Qt Creator). It means you can still do the development with Qt Creator and just re-run step 1 whenever you need to check for memory leaks.

4) To break at a particular memory allocation, use _CrtSetBreakAlloc() More information memory leak detection on Microsoft's website: http://msdn.microsoft.com/en-us/library/e5ewb1h3%28v=vs.80%29.aspx

Solution 2

New 2017 solution

quote by @this.lau_

First, it cannot be done directly in Qt Creator so you need to create a Visual C++ project to do the memory leak detection. Thankfully, qmake makes this easy.

1) Open the Qt SDK command line tool and run:

qmake -spec win32-msvc2015 -tp vc

2) Install Visual Leak Detector for Visual C++

3) Open a .vcxproj that was created with the step 1

4) Include into your main.cpp

#include <vld.h>

5) Launch DebugView v4.81

6) Than run your project ctrl + F5

Solution 3

Here's an even more recent answer. Qt Creator 4.7.1 now supports heob, which is a leak detector too. You can down it for Windows from here: "heob download | SourceForge.net". Extract it somewhere, get a recent version of Qt Creator, and go to Analyze | heob. Direct it to yer .exe, choose yer options, click the little disk icon to save yer opts, and click OK to run yer proggie. It gives u a nice little memcheck window that seems to give you stack dumps at the time the objects were allocated, which u can unfold and see the offending objects; when you use the Detect Leak Types option. You can even navigate to the source line where the new occurred by clicking the link.

JBES supplies the following info:

Optionally download the dwarfstack DLLs for proper stacktrace resolution if you compile with MinGW from dwarfstack DLLs download | github.com and put them in the same folder as the heob executables.

Solution 4

New solution for 2019...

  1. Don't bother making a Visual Studio project.

  2. Install Visual Leak Detector for Visual C++

  3. Include #include <vld.h> in at least one source file.

  4. Add this to your .pro file...

INCLUDEPATH += "C:/Program Files (x86)/Visual Leak Detector/include/" LIBS += -L"C:/Program Files (x86)/Visual Leak Detector/lib/Win64"

  1. On the Project tab, under Build & Run / Run / Run Environment, to the PATH add:

C:\Program Files (x86)\Visual Leak Detector\bin\Win64

If you intend to run the program outside of Qt, you may need to copy dll files (dbghelp and vld_x64) to your build folder, where your program will run. The dlls files are at C:\Program Files (x86)\Visual Leak Detector\bin and you may need to copy vcruntime140.dll or the version of VS that built Visual Leak Detector.

  1. Run qmake, build and develop in Qt-Creator as normal, and the leaks will appear in the Application Output window.

Solution 5

From some version, Deleaker can work as a plugin for Qt Creator. After installation, you can open Deleaker window from the Qt Creator main menu. Once debugging started, Deleaker is monitoring allocations and deallocations. At any moment you can take a snapshot to get list of currently allocated resources (not memory only, but also GDI and others). A video tutorial is available: https://www.youtube.com/watch?v=Fomfpeuc-0o

PS I am from Softanics that is working on Deleaker.

Share:
23,526

Related videos on Youtube

laurent
Author by

laurent

Updated on July 09, 2022

Comments

  • laurent
    laurent almost 2 years

    How can I detect memory leaks in QtCreator on Windows? On the doc, they recommend Memcheck but it only works on Mac and Linux. Any suggestion for Windows?

  • PhilPhil
    PhilPhil about 6 years
    Both answers are excellent, just wanted to add that in later versions of QT substitute the command line qmake -spec win32-msvc2015 -tp vc with qmake -tp vc seem to work. The -spec argument has changed.
  • Anonymouse
    Anonymouse over 5 years
    I found the output from Heob less than useful, it detects 100's of false leaks in even the simplest application (including the demo ones from Qt).
  • CodeLurker
    CodeLurker over 5 years
    Look a little deeper. On the Leak Details setting of the form that comes up when you select Heob, you can select "Detect Leak Types" or choose other options, which change greatly how many hits it shows you. It could be a little less opaque, and have a Qt setting, but I've been using "Detect Leak Types" to some good effect.
  • ssbssa
    ssbssa about 5 years
    Also, try the svg output introduced in heob-3.0. Add -vleaks.svg -g2 to the extra arguments and open the leaks.svg.
  • Silver Zachara
    Silver Zachara about 3 years
    This doesn't work for me, application simple hello world application crash, it builds without problem, also linking against vld is done correctly, but if I try to run it then it crash.