Coming back to life after Segmentation Violation

前端 未结 13 2206
暗喜
暗喜 2020-12-08 11:26

Is it possible to restore the normal execution flow of a C program, after the Segmentation Fault error?

struct A {
    int x;
};
A* a = 0;

a->x = 123; /         


        
13条回答
  •  旧时难觅i
    2020-12-08 12:14

    You can catch segmentation faults using a signal handler, and decide to continue the excecution of the program (at your own risks).

    The signal name is SIGSEGV.

    You will have to use the sigaction() function, from the signal.h header.

    Basically, it works the following way:

    struct sigaction sa1;
    struct sigaction sa2;
    
    sa1.sa_handler = your_handler_func;
    sa1.sa_flags   = 0;
    sigemptyset( &sa1.sa_mask );
    
    sigaction( SIGSEGV, &sa1, &sa2 );
    

    Here's the prototype of the handler function:

    void your_handler_func( int id );
    

    As you can see, you don't need to return. The program's execution will continue, unless you decide to stop it by yourself from the handler.

提交回复
热议问题