Before the problem arises, try to avoid it as much as possible:
- Compile and run your code as often as you can. It will be easier to locate the faulty part.
- Try to encapsulate low-level / error prone routines so that you rarely have to work directly with memory (pay attention to the modelization of your program)
- Maintain a test-suite. Having an overview of what is currently working, what is no more working etc, will help you to figure out where the problem is (Boost test is a possible solution, I don't use it myself but the documentation can help to understand what kind of information must be displayed).
Use appropriate tools for debugging. On Unix:
- GDB can tell you where you program crash and will let you see in what context.
- Valgrind will help you to detect many memory-related errors.
With GCC you can also use mudflap With GCC, Clang and since October experimentally MSVC you can use Address/Memory Sanitizer. It can detect some errors that Valgrind doesn't and the performance loss is lighter. It is used by compiling with the-fsanitize=address
flag.
Finally I would recommend the usual things. The more your program is readable, maintainable, clear and neat, the easiest it will be to debug.