debugging MSVC++ CRTL memory leaks

It seems like none of the docs on this subject are quite complete.

One of the most missed issues is that there can be multiple heaps in a single process. DLLs that use the CRTL, for example, can get a module-local heap. Each heap will get a separate run of the dump activity, so the allocation number shown in the dump report is local to that heap. You might not break in the right place if you don’t set up the allocation break number in the right module.

When I see the “Detected memory leaks!” message, I put a breakpoint in the _CrtDumpMemoryLeaks() function. This function is in dbgheap.c, which installs to C:\Program Files (x86)\Microsoft Visual Studio 12.0\VC\crt\src\dbgheap.c in Visual C++ 2013. It’s the same module that implements _CrtSetDbgFlag() and _CrtSetBreakAlloc(), so stepping into those functions can help open the file.

Breaking on that function’s output of the leaked blocks will reveal the module that’s actually making the call; just look at the module name information in the stack when the breakpoint is hit.

After finding the right module, adding these two lines of code to the application’s InitInstance() method should get the allocator to break on the appropriate allocation number:

_CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF);
_CrtSetBreakAlloc(42530);

The break call might be placed in main() or in DllLoadLibrary(); whatever is the earliest available point. Static constructors run before these methods are called, so it’s conceivable that another static constructor needs to be written to get the hooks all in place early enough.

Some sources show multiple calls to _CrtSetBreakAlloc() implying that the library can check for multiple break numbers — but it can’t.


Posted

in

, ,

by

Tags:

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *