我正在尝试检测内存泄漏,并且我正在使用 make _CRTDBG_MAP_ALLOC 宏来定位泄漏区域。所以我定义宏如下:
#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:内存消耗快速增加,然后缓慢下降;内存泄漏?)
但是输出显示类似:
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.
那么我怎样才能让它显示泄漏的文件名和位置?
似乎只有在该 cpp 文件中打开 CRT 时才会显示泄漏行。
就我而言,我最终将 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.
那么 atldbgmem.h 这个呢?
#include <atldbgmem.h>
#include <crtdbg.h>
atldbgmem.h 包括
#if defined(__ATLBASE_H__) || defined (_INC_CRTDBG)
#error <atldbgmem.h> must be included before other ATL and CRT headers
#endif
...
#define new new(__FILE__, __LINE__)