Tracking memory leaks in Visual Studio

I just discovered this useful piece of code for all who don’t have (including me) any memory leaks tracking code or software.
I know there are other and better solution but this can be handy for quick findings without much hassle.

First place this code in your entry point file, generally main.cpp inside your main() function

#ifdef _DEBUG
	int flag = _CrtSetDbgFlag(_CRTDBG_REPORT_FLAG);
	flag |= _CRTDBG_LEAK_CHECK_DF; // Turn on leak-checking bit
	_CrtSetDbgFlag(flag);
#endif

Now just run you game/program as you would normally, in debug mode of course.

After you close it you’ll get a nice log in the output window like this one:

See those numbers before each memory leak between brackets? Grab one of those and add this line right before the #endif

...
      _CrtSetDbgFlag(flag);
      _CrtSetBreakAlloc(689); // Comment or un-comment on need basis
#endif

Now run the game again, you shall get a break-point where the {689} memory leak happened.

I hope this is the correct way to use it, if not, let me know.

6 Comments

  1. hi,
    have you tried vld (http://vld.codeplex.com/)?
    is pretty easy.

  2. I’ve using that mechanism since I first read “Introduction to 3D Game Programming with DirectX 10″ fom Frank Luna. Extremely useful IMO!
    Though I didn’t knew about the trick to trigger a break point at the line of code where the leak happened… Very helpful! :D

  3. Pingback: Tweets that mention Tracking memory leaks in Visual Studio | David Amador -- Topsy.com

  4. Andrew Karpushin

    Besides that, MSVS has an option to also print a file and line where the leaked allocation occured, _CRTDBG_MAP_ALLOC should be defined. It’s really worked if used properly. http://msdn.microsoft.com/en-us/library/e5ewb1h3(VS.80).aspx

  5. JohnDepth

    I usually use deleaker for debugging – good tool.

Leave a Reply