Using the CRT debug heap for fun and profit
I have to start with the fact that lately whenever I talk with someone about writing code in C++ I feel like Neanderthal or at least very stagnant person. C# 2.0 is on the horizon and it seems that there are only few people left who are trying to get their dosage of adrenaline by playing dangerous games with null-terminated strings and possibility of introducing another double-free bug ;-) Actually I’m just ranting, it’s not so bad, but I promise, honest, I’ll fully switch to C# really soon!
During the last weekend I was writing some "weekend code" which involved tricky pointer manipulations and inevitably I made a mistake and some destructors didn’t get called when application exited. Of course operating system cleans up after the process, but I never feel good while leaving even the slightest memory leaks in the code. Fortunately I remembered my old friend _CrtSetDbgFlag and found a problem in less than five minutes and as a bonus got motivation to write about CRT debug heap.
Hopefully there isn’t a Windows C/C++ programmer in the planet who doesn’t know about existence of DCRT. Famous Bugslayer John Robbins dedicates an entire chapter in his "Debugging Applications for Microsoft® .NET and Microsoft Windows®" for this purpose (Chapter 17, The Debug C Run-Time Library and Memory Management, page 667). It tells you more about DCRT than I ever would, but to get you started here are a couple of fundamental links:
This is just the simplest form of usage:
#define _CRTDBG_MAP_ALLOC
#include <cstdlib>
#include <crtdbg.h>
int main()
{
#ifdef _CRTDBG_MAP_ALLOC
int tmpFlag = _CrtSetDbgFlag(_CRTDBG_REPORT_FLAG);
tmpFlag |= _CRTDBG_LEAK_CHECK_DF;
_CrtSetDbgFlag(tmpFlag);
#endif
...
return EXIT_SUCCESS;
}
Love debug CRT, cherish it, and use it in every one of your C/C++ applications (unless you use some other more advanced ways to manage heap in your applications or don’t use CRT at all). If you’re developer then go and add a couple of these lines into your code and believe me, it’ll make your life easier. If you’re tester then go and open a bug per every C/C++ application which doesn’t use CRT built-in memory leak detection. But make sure you read MSDN first and set the right flags suitable for your specific needs. For example _CRTDBG_CHECK_ALWAYS_DF is quite a big hit to performance and may render your debug builds totally useless for testing purposes.