problem in SIGSEGV signal handling

i wrote handler for sigsegv such that i can allocate memory for a variable to which
sigsegv generated for illlegal acces of memory.

my code is

#include <signal.h>
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
char *j;
void segv_handler(int dummy)
{
  j=(char *)malloc(10);
  strcpy(j,"hello");
  printf("segmentation fault mine j=%s\n",j);
}
main()
{
  signal(SIGSEGV, segv_handler);
  strcpy(j,"hello\n");
  printf("hai\n");
  for (;;)
  {
  }
}

output is :

segmentation fault mine j=hello
segmentation fault mine j=hello
segmentation fault mine j=hello
segmentation fault mine j=hello
segmentation fault mine j=hello
segmentation fault mine j=hello
segmentation fault mine j=hello
.......infinitely repeating above o/p

can i know why my program is behaving like this..
thanks in advance.....

Have a read of this regarding signal handling:

http://beej.us/guide/bgipc/output/html/multipage/signals.html

Regards

The only calls you can safely make in a signal handler are those that are async-signal safe.

FWIW, malloc() and printf() are most certainly not async-signal safe.

What's probably happening is your SIGSEGV handler is also generating a SIGSEGV.

It's not going to rewind your code back to the beginning of that line when the interrupt returns. It'll jump back into where the segfault happened, deep inside libc, which already has a copy of the variable that won't change when you change j. So, that's not going to work.

There's also a problem with calling library calls inside a signal handler. What if, for instance, a SIGSEGV happened right inside malloc(), causing a second malloc() to be called before the first one has finished? The heap may not even be in a valid state at that moment, or may be left in an invalid state when the second one returns. Nothing but system calls are signal-safe unless specifically written to avoid signal interference, and even then, not all system calls.

I also forsee another problem with this design of yours. The signal has no way to know what size buffer is needed. Why not just do this instead?

int main(void)
{
  j=strdup("hello\n");
}

This creates a correct-sized buffer containing "hello\n" for you. You can free it with free() later.

thanks for ur replay..
i got it.:b: