10 October 2009

Setting up the debug memory allocator for native code

This post covers how to set up the debug memory allocator for native code. After following these steps, you will be able to see all your memory leaks tagged with a filename and line number, allowing you to double-click on the error message in the output window and go directly to the spot where the leaking memory was allocated.

First, you need to turn on the debug memory allocator to catch all calls to malloc(), free(), etc. C++ requires a little extra work to catch all calls to operator new, which I'll explain in a bit.

Place the following block in "stdafx.h" or a similar file included by all modules in your project or solution:



#ifdef
_DEBUG

    // Turn on the debug memory allocator with filename and line number trace.

    // This catches all memory leaked via malloc() et al.

    #define _CRTDBG_MAP_ALLOC

    #include <stdlib.h>

    #include <crtdbg.h>

 

    // Map operator new into the debug memory allocator. This requires all

    // modules to define THIS_FILE, which is a good thing because it lets us

    // know when we have a module which is *not* being tracked by the debug

    // memory allocator.

    #define DEBUG_NEW new(_NORMAL_BLOCK, THIS_FILE, __LINE__)

#endif

 


The standard debug memory allocator only tracks calls to malloc(), free(), etc., so you need an extra step to track calls to operator new. In each C++ module, add the following block of code:


#ifdef _DEBUG

    #define new DEBUG_NEW

    static char THIS_FILE[] = __FILE__;

#endif


Finally, in your main() or WinMain(), add the following line of code as near the beginning as possible:


    _CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF);


Please comment if you have any questions.

No comments:

Post a Comment