Here is my code,
#include<signal.h>
#include<stdio.h>
int main(int argc,char ** argv)
{
char *p=NULL;
signal(SIGSEGV,SIG_IGN); //Ignoring the Signal
printf("%d",*p);
printf("Stack Overflow"); //This has to be printed. Right?
return 0;
}
While executing the code, i’m getting segmentation fault. I ignored the signal using SIG_IGN. So I shouldn’t get Segmentation fault. Right? Then, the printf() statement after printing ‘*p’ value must executed too. Right?
Your code is ignoring SIGSEGV instead of catching it. Recall that the instruction that triggered the signal is restarted after handling the signal. In your case, handling the signal didn’t change anything so the next time round the offending instruction is tried, it fails the same way.
If you intend to catch the signal change this
to this
You should probably also use
sigaction()instead ofsignal(). See relevant man pages.In your case the offending instruction is the one which tries to dereference the NULL pointer.
What follows is entirely dependent on your platform.
You can use
gdbto establish what particular assembly instruction triggers the signal. If your platform is anything like mine, you’ll find the instruction iswith rax register holding value 0, i.e.
NULL. One (non-portable!) way to fix this in your signal handler is to use the third argument signal your handler gets, i.e. the user context. Here is an example:This program displays:
It first causes the handler to be executed by attempting to dereference a NULL address. Then the handler fixes the issue by setting rax to the address of variable
n. Once the handler returns the system retries the offending instruction and this time succeeds.printf()receives 100 as its second argument.I strongly recommend against using such non-portable solutions in your programs, though.