_CrtCheckMemory usage example

前端 未结 1 1521
长情又很酷
长情又很酷 2021-02-06 12:10

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

1条回答
  •  醉梦人生
    2021-02-06 12:37

    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 
    #  include 
    #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.

    0 讨论(0)
提交回复
热议问题