Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

_CrtCheckMemory usage example

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?

like image 521
morgancodes Avatar asked Nov 01 '12 15:11

morgancodes


1 Answers

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:

#ifdef _DEBUG
#  define _CRTDBG_MAP_ALLOC
#  define _CRTDBG_MAP_ALLOC_NEW
#  include <crtdbg.h>
#  include <assert.h>
#endif

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.

like image 68
Hans Passant Avatar answered Oct 18 '22 12:10

Hans Passant