1

I was using CRTDBG library to identify memory leaks in visual studio 2019. I need to define "#define _CRTDBG_MAP_ALLOC" macro for getting the line number of the leak occurs. I am unclear that how the macro gets replaced when there is no value to be replaced ??

#define _CRTDBG_MAP_ALLOC
#include <iostream>
#include <crtdbg.h>
using namespace std;

int main()
{
    _CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF);
    int *ptr = (int*)malloc(sizeof(int));
    *ptr = 10;
    //free(ptr);
    return 0;
}

I am a new to c/c++, Kindly help me on this.

Meganathan
  • 21
  • 5

3 Answers3

1

#define _CRTDBG_MAP_ALLOC just tells the preprocessor that _CRTDBG_MAP_ALLOC is defined.

Code can later check if its defined with a #if defined(_CRTDBG_MAP_ALLOC).

Note nowhere do we set or care or check what value its defined to. So doing something like if (_CRTDBG_MAP_ALLOC == 2) doesn't make sense.

But we dont need it to. It just has to exist.

Mike Vine
  • 9,468
  • 25
  • 44
  • There are some tricks you can do, e.g. https://stackoverflow.com/questions/3781520/how-to-test-if-preprocessor-symbol-is-defined-but-has-no-value – MSalters Nov 11 '21 at 15:09
  • @Mike: On that case, then how the line number of the memory leak occurrence will be displayed ?? – Meganathan Nov 11 '21 at 16:59
1

It's simply replaced by the empty string. E.g.

#define FOO 1
std::cout << FOO+1; // expands to 1+1, outputs 2
#undef FOO
#define FOO
std::cout << FOO+1; // expands to +1, outputs 1

But typically these things are checked with #ifdef.

MSalters
  • 173,980
  • 10
  • 155
  • 350
1

This is the method I use and I prefer new and delete in C++:

#define new new(_CLIENT_BLOCK,__FILE__,__LINE__)
void  GetMemoryLeak()
{
    _CrtDumpMemoryLeaks();
}

And the program:

#define _CRTDBG_MAP_ALLOC
#include <iostream>
#include <crtdbg.h>
using namespace std;


#define new new(_CLIENT_BLOCK,__FILE__,__LINE__)

void  GetMemoryLeak()
{
    _CrtDumpMemoryLeaks();
}
int main()
{
    _CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF);
    int* ptr = new int;
    *ptr = 10;
   // delete ptr;
    GetMemoryLeak();
  
    return 0;
}

Output:

Detected memory leaks! Dumping objects -> C:...\Source.cpp(16) : {151} client block at 0x00F1CCB8, subtype 0, 4 bytes long. Data: < > 0A 00 00 00 Object dump complete. The program '[10452] Project7.exe' has exited with code 0 (0x0).

Minxin Yu - MSFT
  • 2,234
  • 1
  • 3
  • 14