Fixing Segmentation faults in C++

前端 未结 6 1821
被撕碎了的回忆
被撕碎了的回忆 2020-11-27 09:44

I am writing a cross-platform C++ program for Windows and Unix. On the Window side, the code will compile and execute no problem. On the Unix side, it will compile however w

6条回答
  •  执念已碎
    2020-11-27 10:25

    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.

提交回复
热议问题