The common runtime libraries have some useful debugging tools contained in crtdbg.h. In that header file is a useful method called _CrtCheckMemory(). This function is used to validate the debug heap. According to MSDN:
The _CrtCheckMemory function validates memory allocated by the debug heap manager by verifying the underlying base heap and inspecting every memory block. If an error or memory inconsistency is encountered in the underlying base heap, the debug header information, or the overwrite buffers, _CrtCheckMemory generates a debug report with information describing the error condition. When _DEBUG is not defined, calls to _CrtCheckMemory are removed during preprocessing.
So it seems like a good idea to put these in your application to check for memory corruptions.
But I found a problem, or a limitation in using this. This method seems to ignore small heap corruptions.
For example, If I wanted to overwrite an array by 5 elements, I would do the following:
While experimenting with this, I found the _CrtCheckMemory() method will not catch this over-run:
While running the above code, I found that the _CrtCheckMemory() remains blissfully ignorant of the memory corruption, returns TRUE to the assert macro, and nothing happens!
Only when I set the variable offset to a value of 6 or higher will _CrtCheckMemory will find and detect something. Using the above code, this will manifest itself (in a debug build) in two assert message boxes:
The first assert:
And the assert arising from the failure condition returned from _CrtCheckMemory to _ASSERTE:
Of course when I set the offset to a big enough value, say 89, I can corrupt something really important and screw up the CRT, and also crash the application on exit.
I have a project that demonstrates his. The project also demonstrates how to dump memory leaks to the output window at the end of program execution.
I’ll try to put the link here: