fork download
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <execinfo.h>
  4. #include <signal.h>
  5. #include <unistd.h>
  6.  
  7. void handler ( int sig ) {
  8. void *array [ 10 ];
  9. size_t size;
  10.  
  11. // get void*'s for all entries on the stack
  12. size = backtrace ( array, 10 );
  13.  
  14. // print out all the frames to stderr
  15. fprintf ( stderr, "Error: signal %d\n", sig );
  16.  
  17. char **buffer = backtrace_symbols ( array, size );
  18.  
  19. if ( buffer == 0 ) {
  20. fprintf ( stderr, "backtrace_symbols" );
  21. exit ( 1 );
  22. }
  23.  
  24. fprintf ( stderr, "Obtained %zd stack frames.\n", size );
  25. for ( size_t i = 0; i < size; i++ ) {
  26. //fprintf ( stderr, "%lu. %s - %p\n", i, buffer [ i ], array [ i ] );
  27. fprintf ( stderr, "%d. %s - %p\n", i, buffer [ i ], array [ i ] );
  28. }
  29. fprintf ( stderr, "\n\n" );
  30.  
  31. free ( buffer );
  32. exit ( 1 );
  33. }
  34.  
  35. void baz ( ) {
  36. int *foo = ( int * ) -1; // Make a bad pointer
  37. printf ( "%d\n", *foo ); // causes segfault
  38. }
  39.  
  40. void bar ( ) {
  41. baz ( );
  42. }
  43.  
  44. void foo ( ) {
  45. bar ( );
  46. }
  47.  
  48. int main ( int argc, char ** argv ) {
  49. signal ( SIGSEGV, handler );
  50. foo ( );
  51. return 0;
  52. }
  53.  
Runtime error #stdin #stdout #stderr 0s 3424KB
stdin
Standard input is empty
stdout
Standard output is empty
stderr
Error: signal 11
Obtained 5 stack frames.
0. ./prog() [0x804868b] - 0x804868b
1. linux-gate.so.1(__kernel_sigreturn+0) [0xb775a400] - 0xb775a400
2. ./prog() [0x804855d] - 0x804855d
3. /lib/i386-linux-gnu/i686/cmov/libc.so.6(__libc_start_main+0xf5) [0xb74748f5] - 0xb74748f5
4. ./prog() [0x8048599] - 0x8048599