If you are not a big company, chances are you cannot afford the commercial programs to check for memory leaks in your program.. This tutorial will give you a free alternative which you can add to your projects.
The 1st thing that we need to do is to include
To make debugging easier, it would be nice if we could get the file and the line no which is causing the leak. Luckily, this can easily be done with some macro trickery
#define DEBUG_NEW new( _NORMAL_BLOCK, __FILE__, __LINE__)
#define DEBUG_NEW new
The _DEBUG macro is defined only for release builds so by encasing the code in #ifdef/#endif quotes, we can ensure that we dont get sub-par code with Release Builds.
_NORMAL_BLOCK is the ordinary memory allocated by our program. Alternatively, we can use _CLIENT_BLOCK which is a special type of memory block (typically used by MFC programs) for objects that require a destructor.
__FILE__ and __LINE___ are predefined ANSI C macros which return The name of the current source file and the line number the current source file respectively.
Now all of our new operator calls three parameter new calls with the __FILE__ and __LINE__ automatically inserted by the pre-compiler.
We can override the new and delete functions to add our own custom tracking methods. We just need to make sure they atleast do what the old new/delete operator functions did.
The only thing remaining is to set the debug flags to enable memory leak detection. Make sure you call this function at the start of your program
// Get Current flag
int flag = _CrtSetDbgFlag(_CRTDBG_REPORT_FLAG) ;
// Turn on leak-checking bit
flag |= (_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF) ;
// Set flag to the new value
The _CrtSetDbgFlag function allows the application to control how the debug heap manager tracks memory allocations by modifying the bit fields of the _crtDbgFlag flag.OR'ing the current _crtDbgFlag flag with _CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF and setting it, the program automatically calls _CrtDumpMemoryLeaks when the program exits.
The _CrtDumpMemoryLeaks function determines whether a memory leak has occurred since the start of program execution. When a leak is found, the debug header information for all the objects in the heap is dumped in a user-readable form.
If you do not set _CRTDBG_LEAK_CHECK_DF, you will need to call _CrtDumpMemoryLeaks yourself.
You can read more about the different flags here
In the next tutorial, we will look at creating a window