Checking Memory Corruption with _CrtCheckMemory – From the Debugger

Edit: In VS2015+ versions this trick is still useful but is a bit different.

There are several ways to locate memory corruptions, but probably the easiest is to spread _CrtCheckMemorys around and pin the culprit (hopefully) in a binary search scheme. This requires recompilation at each search stage and thus can get tedious quickly.

Enter the forgotten, mis-documented, context operator. Turns out there’s a surprising variety of system/CRT operations you can invoke using it, from the debugger, while at a breakpoint (or the debugee is otherwise halted).  Since _CrtCheckMem is implemented in msvcrtXXXd.dll (XXX being VC version), the syntax to invoke it, e.g. in VS2005, is –


Just type it at a watch window, immediate, or even a QuickWatch – anywhere the expression evaluator can find it.

In my case it quickly turned out I miscalculated the number of vertices in a mesh, and wrote beyond the vertex buffer limit. Last breakpoint before the corruption:


And immediately after:


You can probably pull similar stunts with many other CRT debug routines – just not those that directly allocate/deallocate memory.

Would have been nice if VS was smart enough to lookup symbols at least in all loaded module exports, but turns out it’s not yet the case, as of VS2010:


Oh well. Maybe some day.

This entry was posted in Debugging, VC++, Visual Studio. Bookmark the permalink.

2 Responses to Checking Memory Corruption with _CrtCheckMemory – From the Debugger

  1. kbi says:

    What a fantastic trick, this made my day, thanks a lot for sharing!

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 )

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