Debugging memory leaks

One feature you get for free in the Debug build of the xll library is memory leak detection. The class CrtDbg in xll/debug.cpp calls _CrtSetDbgFlag in its constructor and _CrtDumpMemoryLeaks in its destructor (with a little help from #pragma init_seg(lib) to make sure it gets constructed before other objects) to give you a report on any memory that was allocated but not freed. After running an add-in in the debugger, the Output window will inform you where the leaking is taking place.

Detected memory leaks!
Dumping objects ->
{11293} normal block at 0x03C4E330, 8 bytes long.
 Data:  78 E3 C4 03 80 DE C4 03 

See the {11293} in curly braces? That is where you should set a breakpoint. You do this by calling _CrtSetBreakAlloc(11293) when the add-in is loaded using Auto<Open>, or setting the global variable _crtBreakAlloc = 11293.

Now when you rerun the add-in the debugger will stop at the point where the memory is being allocated and you can peruse the call stack to try and figure out why it isn’t being deallocated. Wouldn’t it be great if it could break at the point where you should be deallocating it? Welcome to the world of C++, big primate with a dollop of grey matter.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s