Nic*_*sui 19 c++ debugging memory-leaks crtdbg.h
我正在尝试检测内存泄漏,我正在使用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
Run Code Online (Sandbox Code Playgroud)
在我的代码中,我有:
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;
}
Run Code Online (Sandbox Code Playgroud)
(感谢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
Run Code Online (Sandbox Code Playgroud)
而不是像这样的东西:
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.
Run Code Online (Sandbox Code Playgroud)
那么如何让这个显示泄漏的文件名和位置?
Krø*_*lle 11
在我的情况下,我最终将这个帖子中的东西包含在我的代码中.这将覆盖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
Run Code Online (Sandbox Code Playgroud)
引用来源的整个测试代码是:
#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;
}
Run Code Online (Sandbox Code Playgroud)
在我的测试用例中打印:
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.
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
12561 次 |
| 最近记录: |