Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Handle SIGSEGV and print back trace on receiving SIGSEGV in c/C++ program?

Tags:

c++

I m constructing a C++ program in which I need to handle SIGSEGV and Signal handler should be able to print the Back Trace. Can any one help in this.

Regards

like image 855
Ravi Varshney Avatar asked May 14 '10 08:05

Ravi Varshney


2 Answers

The best way to get a SIGSEV backtrace is generating a core file more than printing a backtrace. Take care beacause if you handle SIGSEV the system will not call the default core generator.

If you want to handle the SIGSEV anyway (as have been commented before this is system deppendant), see the libc backtrace function [http://www.gnu.org/s/libc/manual/html_node/Backtraces.html ] , it could be useful.

like image 198
Jon Ander Ortiz Durántez Avatar answered Sep 21 '22 00:09

Jon Ander Ortiz Durántez


Adding to what Jon replied, you basically need a function like this to print backtrace. This function shoudl be called on the SIGSEGV. But I second Jon's point that letting the system generate corefile would be a much better debugging mechanism for you

void print_trace(int nSig)
{
  printf("print_trace: got signal %d\n", nSig);

  void           *array[32];    /* Array to store backtrace symbols */
  size_t          size;     /* To store the exact no of values stored */
  char          **strings;    /* To store functions from the backtrace list in ARRAY */
  size_t          nCnt;

  size = backtrace(array, 32);

  strings = backtrace_symbols(array, size);

  /* prints each string of function names of trace*/
  for (nCnt = 0; nCnt < size; nCnt++)
    fprintf(stderr, "%s\n", strings[nCnt]);


  exit(-1);
}
like image 30
rajeshnair Avatar answered Sep 22 '22 00:09

rajeshnair