C – Segment fault handling

Segment fault handling… here is a solution to the problem.

Segment fault handling


have an application that I can use to catch any segfault or ctrl-c.
Using the code below, I was able to catch the segfault, but the handler was called again and again. How can I stop them.
For your reference, I don’t want to quit my app. I can take care to free all corrupted buffers.

Is this possible?

void SignalInit(void )

struct sigaction sigIntHandler;

sigIntHandler.sa_handler = mysighandler;
sigIntHandler.sa_flags = 0;
sigaction(SIGINT, &sigIntHandler, NULL);
sigaction(SIGSEGV, &sigIntHandler, NULL);


The handler looks like this.

void mysighandler()
MyfreeBuffers(); /*related to my applciation*/

Here is the segfault signal, the handler has been called several times, and it is clear that MyfreeBuffers() gives me an error that frees the memory that has been freed. I just want to release it once but still don’t want to quit the app.

Please help.


The default action such as SIGSEGV is to terminate your process, but when you install a handler for it, it calls your handler to override the default behavior. But the problem is that the segfault instruction may be retried after your handler completes, and if you do not take action to fix the first segfault, the retried instruction will error again and continue.

So first find out the instruction that is causing SIGSEGV and try to fix it (you can call something like backtrace() in the handler and see for yourself what goes wrong).

In addition, the POSIX standard says

The behavior of a process is undefined after it returns normally from
a signal-catching function for a [XSI] SIGBUS, SIGFPE, SIGILL, or
SIGSEGV signal that was not generated by kill(), [RTS] sigqueue(),
or raise().

Therefore, the ideal is to fix your segfault first. The segfault handler does not imply bypassing the underlying error condition

So the best advice is – do not capture SIGSEGV. Let it dump the core. Analyze the core. Fix invalid memory references and you’re good to go!

Related Problems and Solutions