Memory Leak Woes

This entry was posted on
  • Snippet
  • Tutorial
  • cpp

Finding Memory Leaks

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 crtdbg.h.

Note: crtdbg.h should be added after all the other header files

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

#ifdef _DEBUG
#define DEBUG_NEW new( _NORMAL_BLOCK, __FILE__, __LINE__)
#define DEBUG_NEW new

The DEBUG macro is defined only for Debug builds so by encasing the code in #ifdef/#endif quotes, we can ensure that we don’t get sub-par code in our 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 in the file respectively.

Now, whenever we allocate memory using DEBUG_NEW (in Debug mode ) the _FILE_ and _LINE_ is automatically inserted by the pre-compiler into the new operator call.

Note: We can override the new and delete functions to add our custom tracking methods. We just need to make sure they at least 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

void CheckForMemoryLeaks()
#ifdef _DEBUG
    // Get Current flag
    int flag = _CrtSetDbgFlag(_CRTDBG_REPORT_FLAG) ;

    // Turn on leak-checking bit

    // Set flag to the new value
    _CrtSetDbgFlag(flag) ;
#endif _DEBUG

The _CrtSetDbgFlag function allows the application to control how the debug heap manager tracks memory allocations. It does this 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.

Additional Reading

You can read more about the different flags here