问题
How to detect memory overrun in your 24/7 application, such as an online game server? The system and tool is linux + gcc.
Sometimes the cause of the memory overrun is writing the memory beyond the array; and sometimes the cause of the memory overrun is invalid pointers.
So, does anyone have some experience with this and know how to prevent it?
回答1:
Prevention (at code level):
- Watch out the warnings of your compiler
- Use a static code checker
- Use strong coding guidelines
Detection (at run-time):
- Use tools like valgrind, efence, ... to analyse the behaviour of your program
回答2:
You redefine your memory allocation function (e.g. malloc
) to allocate a bigger buffer than is needed to store the allocation, and you fill the additional space with known pattern, and you regularly check that the pattern has not been corrupted.
回答3:
As others have said, use valgrind
during testing, and test exhaustively. For protection at run-time, it's possible to replace the global operator new
and operator delete
: the replacements should maintain a guard block on both sides of the returned block: operator new
initializes the guard blocks to a predefined pattern, and operator delete
verifies that that pattern is still present. operator delete
should also overwrite the actual memory with a distinctive pattern (not all 0's), to increase the probability that using a dangling pointer will be detected.
Using std::vector
, and particularly a debugging version of std::vector
, for all arrays, should prevent all overwriting, and detect it immediately, at the site it occurs (as opposed to when you finally free the memory). The performance hit might be too much to leave all of the checking in the final application, however (but it's worth a try).
回答4:
Run your program using valgrind's memory check.
Unit test you code as much as possible, and again execute then using valgrind's memory check.
来源:https://stackoverflow.com/questions/8309308/how-to-detect-a-memory-overrun