This problem maybe has no specific answer appropriate for all situations,but is there some general principle we can respect? Overwrite happened in own module may be a little easy,but if the overwrite is caused by another module written by other people and the program crashed random, how we can do for these?
2 Answers
I have had a lot of luck with a product called Purify, that performs memory bounds checking, after you include it at compile time. The Wikipedia page I linked to also lists some open source alternatives.
1 Comment
Memory overwrite is often caused by dangling pointers. While this is not the only case, it's quite common and so I've found one technique that's pretty useful:
By implementing your own memory allocator you can turn on a special debug mode where you write some known pattern into freed memory. You then periodically check all free memory to see if the pattern has been overwritten. If it has you assert or log or something. This will often find the culprit that's writing to some dangling pointer.
In addition, you can use the custom allocator to log the allocations made by address. So if you see that someone has overwritten address 0x30203 you can just check who that memory was allocated to.
I realize this sounds like a special case, but it's helped me out of so many cases before
valgrindto identify abuses of the dynamically allocated memory. Dealing with overwrites of static data or stack data is harder. The tool Purify from IBM is also very good, but more expensive thanvalgrind.