I'm trying to understand how to use _CrtCheckMemory
to track down heap corruption in a Windows application I'm working on. I can't seem to get it to return false
. Here's my test code:
int* test = new int[1];
for(int i = 0; i < 100; i++){
test[i] = 1;
}
assert( _CrtCheckMemory( ) );
In the code above, _CrtCheckMemory( )
returns true. I'm running in Debug mode. What else do I need to do in order to get a simple example of _CrtCheckMemory
flagging a problem?
An extra step is required, you must convince the compiler to replace the default new operator with the debug allocator. Only the debug allocator creates the "no-mans land" areas that detect an under- or overwrite of the heap block. It is risky, code that's compiled with the original allocator will not mix well with code that wasn't. So it forces you to opt-in explicitly.
That's best done in the pre-compiled header file (stdafx.h by default) so you can be sure that all code uses the debug allocator. Like this:
The CRTDBG macros get the malloc() functions and the new operators replaced.
Do beware that your code as posted will trigger another diagnostic first. On Windows Vista and up, the Windows heap allocator is going to complain first because the code destroyed the Windows heap integrity. Make the overwrite a bit subtler by indexing only up to, say, 2.