Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why signal handler goes to infinite loop? - SIGSEGV

Tags:

c

linux

Any idea why the signal handler goes to infinite loop?

Here is the code. Please help me.

enter code here
 9 void SIGSEGV_handler(int signal)
10 {
11  printf("Segmentation fault caught....\n");
12  printf("Value of instance variable: i = %d\n\n", i);
13 } 
16 
17 int main()
18 {
19  char *mallocPtr, *callocPtr, *reallocPtr, *memalignPtr, *vallocPtr;
20  struct sigaction sa;
21 
22  sa.sa_handler=SIGSEGV_handler;
23  sigaction(SIGSEGV, &sa, NULL);
24 
37 
38  printf("The segmentation fault handler will be entered for i = 3, 4, 5 and 6\n");
39 
40 
41  for(i=0; i<7; i++)
42   {
43    printf("i = %d\n",i);
44 
45    mallocPtr=(char*)malloc(3);
46    printf("Malloc address : %x\n",mallocPtr);
47    strcpy(mallocPtr, "Hhvhgvghsvxhvshxv");
48    puts(mallocPtr);
like image 815
RajSanpui Avatar asked Aug 08 '11 11:08

RajSanpui


1 Answers

The default action for SIGSEGV is to terminate your process. But you install a handler and override this:

/* Does nothing to "fix" what was wrong with the faulting
 * instruction.
 */
void SIGSEGV_handler(int signal)
{
    printf("Segmentation fault caught....\n");
    printf("Value of instance variable: i = %d\n\n", i);
}

So for every instruction that triggers a sigsegv, this handler is called and the instruction is restarted. But your handler did nothing to fix what was wrong in the first place with the faulting instruction.

In conclusion, when the instruction is restarted, it will fault again. And again, and again and... you get the idea.

like image 120
cnicutar Avatar answered Nov 05 '22 15:11

cnicutar