title: Backtrace inside Signal Handler
body: <p>I'm trying to following the code from <a href="https://stackoverflow.com/questions/3151779/how-its-better-to-invoke-gdb-from-program-to-print-its-stacktrace/4611112#4611112">this post</a> to have signal handlers print a backtrace on errors such as floating point and segmentation faults. I'm using seg fault signals as a starting point. Here is the code:</p>
  
  <pre><code>#include &lt;cstdlib&gt;      //for exit()
  #include &lt;signal.h&gt;     //signal handling   
  #include &lt;execinfo.h&gt;   //backtrace, backtrace_symbols and backtrace_fd
  #include &lt;iostream&gt;
  #include &lt;string.h&gt;
  #include &lt;stdio.h&gt;
  
  #define TRACE_MSG fprintf(stderr, "TRACE at: %s() [%s:%d]\n", \
          __FUNCTION__, __FILE__, __LINE__)
  
  void show_stackframe()
  {
      void *trace[1024];
      char **messages = (char **) NULL;
      int i, trace_size = 0;
      TRACE_MSG;
      trace_size = backtrace(trace, 1024);    // segfault here???
      // More code here to print backtrace, but not needed at the moment..
      TRACE_MSG;
  }
  
  void sigSegvHandler( int signum, siginfo_t* info, void* arg )
  {
      TRACE_MSG;
      show_stackframe();
      return;
  }
  
  double func_b()
  {
      show_stackframe();  // Show that backtrace works without being 
                      // called inside sighandler.
  
      TRACE_MSG;
      int int_a[5];
      int_a[0] = 4;
      int_a[11] = 10;         // cause a segfault on purpose to see
                      // how the signal handling performs.
  
      return 1.1;
  }
  
  int main()
  {
      // Examine and change the seg fault signal
      struct sigaction segvAction;   // File: /usr/include/bits/sigaction.h
  
     // Initialize segvAction struct to all zeros for initialiation
     memset( &amp;segvAction,  0, sizeof( segvAction ) );
  
     segvAction.sa_sigaction = sigSegvHandler;
     segvAction.sa_flags = SA_SIGINFO;    //Invoke signal catching function with 3 arguments instead of 1
  
     // Set the action for the SIGSEGV signal
     sigaction( SIGSEGV, &amp;segvAction,  NULL );
  
     func_b();    // Produce a SIGSEGV error
  }
  </code></pre>
  
  <p>I am compiling using:</p>
  
  <pre><code> g++ -rdynamic testprogram.cpp -o testprogram
  </code></pre>
  
  <p>I receive the following output from the program:</p>
  
  <pre><code>TRACE at: show_stackframe() [stackoverflow.cpp:15]
  TRACE at: show_stackframe() [stackoverflow.cpp:17]
  TRACE at: func_b() [stackoverflow.cpp:33]
  TRACE at: sigSegvHandler() [stackoverflow.cpp:22]
  TRACE at: show_stackframe() [stackoverflow.cpp:15]
  Segmentation fault
  </code></pre>
  
  <p>My question is why does show_stackframe() cause a segmentation fault inside of sigaction but works fine when not inside of the sigaction handler? I obviously seem to be setting up the signal handler/action incorrect but I haven't been able to find it all day. GDB doesn't seem to be any help in this case.</p>