What causes a SIGSEGV

后端 未结 7 905
野性不改
野性不改 2020-11-27 15:52

I need to know the root cause of the segmentation fault (SIGSEGV), and how to handle it.

相关标签:
7条回答
  • 2020-11-27 16:44

    Here is an example of SIGSEGV.

    root@pierr-desktop:/opt/playGround# cat test.c
    int main()
    {
         int * p ;
         * p = 0x1234;
         return 0 ;
    }
    root@pierr-desktop:/opt/playGround# g++ -o test test.c  
    root@pierr-desktop:/opt/playGround# ./test 
    Segmentation fault
    

    And here is the detail.

    How to handle it?

    1. Avoid it as much as possible in the first place.

      Program defensively: use assert(), check for NULL pointer , check for buffer overflow.

      Use static analysis tools to examine your code.

      compile your code with -Werror -Wall.

      Has somebody review your code.

    2. When that actually happened.

      Examine you code carefully.

      Check what you have changed since the last time you code run successfully without crash.

      Hopefully, gdb will give you a call stack so that you know where the crash happened.


    EDIT : sorry for a rush. It should be *p = 0x1234; instead of p = 0x1234;

    0 讨论(0)
提交回复
热议问题