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

本文介绍了如何在Windows上使用Visual C项目检测Qt Creator中的内存泄漏。通过qmake将项目转换为.vcproj,然后在main.cpp中添加内存泄漏检测代码,利用_CrtDbgReport进行内存泄露报告,并定制报告钩子过滤掉Qt自身的内存泄漏。在应用程序执行完毕后,调用_CrtDumpMemoryLeaks()显示内存泄漏信息。
摘要由CSDN通过智能技术生成

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

1)首先,它不能直接在Qt Creator中完成,因此您需要创建一个Visual C项目来进行内存泄漏检测.幸运的是,qmake使这很容易.打开Qt SDK命令行工具并运行:

qmake -spec win32-msvc2008 -tp vc

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

2)打开此项目并添加内存泄漏检测所需的代码:

到你的main.cpp文件:

// Necessary includes and defines for memory leak detection:

#ifdef _MSC_VER

#define _CRTDBG_MAP_ALLOC

#include

#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)为此,您的项目现在应该能够检测内存泄漏.注意_MSC_VER定义,以便只有当您从Visual C(而不是来自Qt Creator)运行此代码时才执行此代码.这意味着您仍然可以使用Qt Creator进行开发,只要您需要检查内存泄漏,就重新运行步骤1.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值