如何在 Windows 上的 QtCreator 中检测内存泄漏?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6825376/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-15 17:35:34  来源:igfitidea点击:

How to detect memory leaks in QtCreator on Windows?

c++windowsmemory-leaksqt-creatordetect

提问by laurent

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?

如何在 Windows 上的 QtCreator 中检测内存泄漏?在文档上,他们推荐 Memcheck,但它仅适用于 Mac 和 Linux。对 Windows 有什么建议吗?

回答by laurent

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

经过多次尝试,我终于找到了一种在 Windows 上检测 Qt 项目内存泄漏的方法:

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:

1)首先,不能直接在Qt Creator中进行,所以需要创建一个Visual C++工程来进行内存泄漏检测。值得庆幸的是,qmake 使这变得容易。打开 Qt SDK 命令行工具并运行:

qmake -spec win32-msvc2008 -tp vc

This will convert your project to a .vcproj.

这会将您的项目转换为 .vcproj。

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

2)打开这个项目,添加必要的内存泄漏检测代码:

To your main.cppfile:

到您的main.cpp文件:

// 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_VERdefines 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.

3) 有了这个,您的项目现在应该能够检测内存泄漏。请注意_MSC_VER定义,以便此代码仅在您从 Visual C++(而不是从 Qt Creator)运行时执行。这意味着您仍然可以使用 Qt Creator 进行开发,只需在需要检查内存泄漏时重新运行步骤 1。

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

4) 要中断特定的内存分配,请使用_CrtSetBreakAlloc()Microsoft 网站上的更多信息内存泄漏检测:http: //msdn.microsoft.com/en-us/library/e5ewb1h3%28v=vs.80%29.aspx

回答by Mikhail

New 2017 solution

新的 2017 解决方案

quote by @this.lau_

引用者 @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.

首先,它不能直接在 Qt Creator 中完成,因此您需要创建一个 Visual C++ 项目来进行内存泄漏检测。值得庆幸的是,qmake 使这变得容易。

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

1)打开Qt SDK命令行工具,运行:

qmake -spec win32-msvc2015 -tp vc

qmake -spec win32-msvc2015 -tp vc

2) Install Visual Leak Detector for Visual C++

2)为 Visual C++安装Visual Leak Detector

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

3)打开一个用步骤创建的.vcxproj 1

4) Include into your main.cpp

4) 包含在你的 main.cpp

#include <vld.h>

#include <vld.h>

5) Launch DebugView v4.81

5) 启动DebugView v4.81

6) Than run your project ctrl + F5

6)比运行你的项目 ctrl + F5

回答by CodeLurker

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.

这是一个更新的答案。Qt Creator 4.7.1 现在支持 heob,它也是一个泄漏检测器。您可以从这里为 Windows下载它:“heob 下载 | SourceForge.net”。将其解压到某处,获取最新版本的 Qt Creator,然后转到分析 | 赫布。将它定向到 yer .exe,选择 yer 选项,单击小磁盘图标保存 yer opts,然后单击 OK 运行 yer proggie。它提供了一个漂亮的小内存检查窗口,似乎在分配对象时为您提供堆栈转储,您可以展开并查看有问题的对象;当您使用检测泄漏类型选项时。您甚至可以通过单击链接导航到新出现的源代码行。

回答by Anonymouse

New solution for 2019...

2019年新解决方案...

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

1) 不要费心制作 Visual Studio 项目。

2) Install Visual Leak Detector for Visual C++

2)为 Visual C++安装Visual Leak Detector

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

3) 包含#include <vld.h>在至少一个源文件中。

4) Add this to your .profile...

4)将此添加到您的.pro文件...

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

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

5) On the Projecttab, under Build & Run / Run / Run Environment, to the PATHadd:

5) 在Project选项卡上的 下Build & Run / Run / Run EnvironmentPATH添加:

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

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

6) Run qmake, build and develop in Qt-Creator as normal, and the leaks will appear in the Application Outputwindow.

6)qmake在Qt-Creator中正常运行,构建和开发,Application Output窗口中会出现泄漏。

回答by Artem Razin

From some version, Deleakercan 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

从某些版本开始,Deleaker可以作为 Qt Creator 的插件工作。安装后,您可以从 Qt Creator 主菜单中打开 Deleaker 窗口。一旦调试开始,Deleaker 就会监控分配和释放。您可以随时拍摄快照以获取当前分配的资源列表(不仅是内存,还有 GDI 和其他资源)。提供视频教程:https: //www.youtube.com/watch?v=Fomfpeuc-0o

PS I am from Softanics that is working on Deleaker.

PS 我来自从事 Deleaker 的 Softanics。

回答by user2019716

when using visual studio, it is important to note that if your mainwindow is created on the stack like so :

使用 Visual Studio 时,请务必注意,如果您的主窗口是在堆栈上创建的,如下所示:

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    MainWindow w;
    w.show();
    int result = a.exec();
    _CrtDumpMemoryLeaks();
    return result;
}

Many false positive will appear if you dinamically allocate memory in you Qt objects. To avoid it, one can to modify the code to create the window object on the heap and execute the function _CrtDumpMemoryLeaks()after deletion of the mainwindow instance:

如果您动态地在 Qt 对象中分配内存,则会出现许多误报。为了避免这种情况,可以修改代码在堆上创建窗口对象,并_CrtDumpMemoryLeaks()在删除主窗口实例后执行该函数:

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    MainWindow * = new w;
    w->show();
    int result = a.exec();
    delete w;
    _CrtDumpMemoryLeaks();
    return result;
}