Thursday, December 20, 2007

Memory Debugging with VC8

Want to check how many hundreds of memory leaks you have?

Using the microsofts CRT debug heap is an easy way of doing it.

To get a listing of all memory leaks, you simply need to include crtdbg.h, set the debug flag, using the function _CrtSetDbgFlag and run your code in debug mode. The leaks will appear in the output tab.

To get started with it here is the minimal code to implement it:

#include 
int flag = _CrtSetDbgFlag(_CRTDBG_REPORT_FLAG);
flag |= _CRTDBG_LEAK_CHECK_DF; // Turn on leak-checking
_CrtSetDbgFlag(flag); // Set flag to the new value

To turn it off:
// Turn off CRT block checking bit
tmpFlag &= ~_CRTDBG_CHECK_CRT_DF;
This will only tell you how many leaks you have. To be really useful you want to know which calls to new are causing the memory leaks. In order for MSVC IDE to point to the lines of code which allocate the memory that causes the leak, simply redefine new as such:

#define new new(_NORMAL_BLOCK,__FILE__, __LINE_)

Finally if you get a memory leak you can set a breakpoint at a secific

Finally if you get a memory leak you can set a breakpoint at a specific allocation number by using:

_CrtSetBreakAlloc(2825);
with 2825 being the allocation nb shown in {} in the error message.

Et voila!
Simple no?

No comments: