Memory corruptions are one of the toughest problems to debug. Part of the problem is that the errors are manifested only late into the programs lifetime, after the original corruption happened.It usually manifests as a dump, involving RtlAllocateHeap routine.
There are a couple of ways to solve this issue
- Move to Java or C# or VB or Ruby …. you get the idea
- Use an expensive tool like Purify or BoundsChecker
- Use a free tool
My latest discovery in this area is PageHeap.
Whats cool about this tool ?
- This is a system provided tool and written by the same folks at Microsoft.
- It is precise. No more wading through lists of false positives to find the error.
- It integrates well with system debuggers like Windbg.
- It can debug the heap operations performed by only certain dlls that are loaded by the process.
- It can perform a full list of checks including multiple frees / access after free etc. See the full list here
Hows does it work?
It raises an exception whenever an access violation is sensed. This will typically cause programs to break into the debugger on the instruction which caused the violation.
All you have to is –
pageheap /enable <yourappname.exe> /full [/dlls list of dlls]
Caveat – This tool works by raising access violation exceptions. So if you are trapping all exceptions using the ubiquitous catch(…) then the access violation will not be reported.
To overcome this restriction all that has to be done, is to enable the Access violation event filter status in the debugger. This will cause the debugger to break as soon as it senses an exception instead of letting the program handle it (First chance exception handling).
NOTE : You can also use the glags tool from the windgb install to achieve the same.