我正在尝试检测内存泄漏,我正在使用make _CRTDBG_MAP_ALLOC宏来查找泄漏区域。所以我定义MACRO如下:
#ifdef _DEBUG
#define _CRTDBG_MAP_ALLOC
#include <stdlib.h>
#include <crtdbg.h>
#define DEBUG_NEW new(_NORMAL_BLOCK, __FILE__, __LINE__)
#define new DEBUG_NEW
#endif
在我的代码中,我有:
UINT SomeFunThread( LPVOID pParam )
{
_CrtMemState crtMemStateStart;
_CrtMemState crtMemStateFinish;
_CrtMemCheckpoint(&crtMemStateStart);
// My suspisious code
_CrtMemCheckpoint(&crtMemStateFinish);
int nDifference(0);
_CrtMemState crtMemStateDifference;
nDifference = _CrtMemDifference(&crtMemStateDifference, &crtMemStateStart, &crtMemStateFinish);
if(nDifference > 0)
_CrtDumpMemoryLeaks();
return 0;
}
(感谢Tushar Jadhav:Memory consumption increases quickly, then drops very slowly; memory leak?)
但输出显示如下:
Detected memory leaks!
Dumping objects ->
{124058} normal block at 0x0000000031DED080, 24 bytes long.
Data: < 0 ` $ > C8 30 F7 EF FE 07 00 00 60 D2 24 1D 00 00 00 00
而不是像这样:
Detected memory leaks!
Dumping objects ->
C:\PROGRAM FILES\VISUAL STUDIO\MyProjects\leaktest\leaktest.cpp(20) : {18}
normal block at 0x00780E80, 64 bytes long.
Data: < > CD CD CD CD CD CD CD CD CD CD CD CD CD CD CD CD
Object dump complete.
那么如何让这个显示泄漏的文件名和位置?
答案 0 :(得分:12)
在我的情况下,我最终将this线程中的内容包含在我的代码中。这会覆盖new
运算符,并包含文件名和行号以便以后打印。不确定这是否仅适用于Visual Studio。
#define _CRTDBG_MAP_ALLOC
#include <crtdbg.h>
#ifdef _DEBUG
#define DEBUG_NEW new(_NORMAL_BLOCK, __FILE__, __LINE__)
#define new DEBUG_NEW
#endif
来自参考来源的整个测试代码是:
#define _CRTDBG_MAP_ALLOC
#include<iostream>
#include <crtdbg.h>
#ifdef _DEBUG
#define DEBUG_NEW new(_NORMAL_BLOCK, __FILE__, __LINE__)
#define new DEBUG_NEW
#endif
int main()
{
char *a = new char[10];
_CrtDumpMemoryLeaks();
return 0;
}
在我的测试用例中打印:
Detected memory leaks!
Dumping objects ->
e:\test\testapplication\testapplication.cpp(11) : {144} normal block at 0x007F4EF0, 10 bytes long.
Data: < > CD CD CD CD CD CD CD CD CD CD
Object dump complete.
答案 1 :(得分:6)
如果在该cpp文件中打开CRT,似乎只显示泄漏线。