How do I diagnose heap corruption errors on Windows?
The @Carlos's solution is perfect for smaller problems. But for huge problems, the resulting slow down is sometimes something you cannot stomach.
In this case, one can place
ASSERT(_CrtCheckMemory());
somewhere in the code, where one suspects the problem already to be present. This command checks the heap at (and only at) the spot it is inserted, and not after every new
or delete
call as in the case of _CRTDBG_CHECK_ALWAYS_DF
. This keeps the execution time reasonable, compared to option _CRTDBG_CHECK_ALWAYS_DF
.
One can find the problematic line of code pretty quickly by using a binary search kind of approach for placing the asserts.
However, sometimes _CrtSetDbgFlag(_CRTDBG_CHECK_ALWAYS_DF)
and/or _CrtCheckMemory()
aren't able to detect problems. Then using gflags
is another possibility, which is able to show where the heap-corruption happens. In a nutshell:
- enable page heap (usually you would need admin's priveleges), e.g.:
there will be a report, that heap checks for"C:\Program Files (x86)\Windows Kits\10\Debuggers\x64\gflags.exe" /p /enable <full_path_to_exe_to_debug.exe> /full
exe_to_debug.exe
were activated. - run program in debugger. Accesses out of bounds, which would corrupt the heap lead now to access violation and are easily seen in the the debugger.
- disable page heap once debugging is done, e.g.:
"C:\Program Files (x86)\Windows Kits\10\Debuggers\x64\gflags.exe" /p /disable <full_path_to_exe_to_debug.exe>
- programs with activated heap check can be listed via
"C:\Program Files (x86)\Windows Kits\10\Debuggers\x64\gflags.exe" /p
Use the debug heap and call this at the very beginning in main().
_CrtSetDbgFlag(_CRTDBG_CHECK_ALWAYS_DF);
It will slow down the program a lot but it should break as soon as corruption occurs.
Refer to this article for details: https://msdn.microsoft.com/en-us/library/974tc9t1.aspx#BKMK_Check_for_heap_integrity_and_memory_leaks