Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the usage of DEBUG_NEW and __FILE__?

Tags:

c++

I saw the follow macros,

#ifdef _DEBUG
#define new DEBUG_NEW
#UNDEF THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif

What is the usage of above macro?

Thank you

like image 260
q0987 Avatar asked Mar 24 '11 15:03

q0987


2 Answers

DEBUG_NEW is just a MACRO which is usually defined as:

#define DEBUG_NEW new(__FILE__, __LINE__)
#define new DEBUG_NEW

So that wherever you use new, it also can keep track of the file and line number which could be used to locate memory leak in your program.

And __FILE__, __LINE__ are predefined macros which evaluate to the filename and line number respectively where you use them!

Read the following article which explains the technique of using DEBUG_NEW with other interesting macros, very beautifully:

A Cross-Platform Memory Leak Detector


From Wikpedia,

Debug_new refers to a technique in C++ to overload and/or redefine operator new and operator delete in order to intercept the memory allocation and deallocation calls, and thus debug a program for memory usage. It often involves defining a macro named DEBUG_NEW, and makes new become something like new(_FILE_, _LINE_) to record the file/line information on allocation. Microsoft Visual C++ uses this technique in its Microsoft Foundation Classes. There are some ways to extend this method to avoid using macro redefinition while still able to display the file/line information on some platforms. There are many inherent limitations to this method. It applies only to C++, and cannot catch memory leaks by C functions like malloc. However, it can be very simple to use and also very fast, when compared to some more complete memory debugger solutions.

like image 182
Nawaz Avatar answered Oct 23 '22 16:10

Nawaz


_DEBUG is an arbitrarily named, but often chosen, command line symbol which indicates that extra code and support for debugging the program should be compiled in. Often this causes extra checks to help isolate programming flaws, or causes extra messages to be output for the benefit of the developer.

DEBUG_NEW isn't clear, but it is probably an alias for new() which does extra validation associated with new() and delete().

__FILE__ is a built-in preprocessor symbol which evaluates to the filename of the module being compiled. For example "MyProgram.cc".

like image 1
wallyk Avatar answered Oct 23 '22 17:10

wallyk