_CRTDBG_MAP_ALLOC not showing file name

2019-03-18 01:33发布

I am trying to detect memory leak, and I am using make _CRTDBG_MAP_ALLOC macro to locate where the leaks area. So I am defining MACRO like following:

#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

In my code, I have:

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;
}

(Thanks to Tushar Jadhav: Memory consumption increases quickly, then drops very slowly; memory leak?)

But the output shows something like:

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 

instead of something like this:

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.

So how can I make this show the file name and location of the leak?

2条回答
不美不萌又怎样
2楼-- · 2019-03-18 01:50

In my case I ended up including the stuff from this thread into my code. This overrides the new operator and includes the name of the file and the line number into it for later printing. Not sure if this is applicable to Visual Studio only.

#define _CRTDBG_MAP_ALLOC
#include <crtdbg.h>
#ifdef _DEBUG
#define DEBUG_NEW new(_NORMAL_BLOCK, __FILE__, __LINE__)
#define new DEBUG_NEW
#endif

The whole test code from the referenced source is:

#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; 
}

which in my test case prints:

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.
查看更多
ゆ 、 Hurt°
3楼-- · 2019-03-18 02:03

It seems the line of the leak only is displayed if the CRT is turned on in that cpp file.

查看更多
登录 后发表回答