Saturday, 7 July 2018

segment fault and signal Abort

#include 
#include 
#include 
#include 
#include 

void handler(int sig) {
  size_t nStackTraces = 20; //number of backtraces you want at most
  void *array[nStackTraces];
  size_t size;
  //fills array and returns actual number of backtraces at the moment
  size = backtrace(array, nStackTraces);
  printf("signal no %d \n", sig);

  //prints array to std error after converting array to
  //human-readable strings
  backtrace_symbols_fd(array, size, STDERR_FILENO);
  exit(0);
}

int function1(){
   int *myUninitiliazedPointer = 0;
   *myUninitiliazedPointer = 1; //opps here comes segmentation fault
   return 0;
}

void function0(){
  function1();
}

int main() {
    signal(SIGSEGV , handler);   // register our handler
    function0();
    return 0;
}
You can comment out first line to see our beloved segmentation fault :( .
Segmentation fault (core dumped)
It is output in my linux :
signal no 11
./a.out[0x4008b5]
/lib/x86_64-linux-gnu/libc.so.6(+0x36ff0)[0x7f8ac8b33ff0]
./a.out[0x40090d]
./a.out[0x400923]
./a.out[0x40094c]
/lib/x86_64-linux-gnu/libc.so.6(__libc_start_main+0xf5)[0x7f8ac8b1ede5]
./a.out[0x400759]
Which is not very helpful. It seems to get more meaningful output, one needs to compile its code with -g -rdynamic flags.
gcc -g -rdynamic sampleCode.c
After that its output changes to:
./a.out(_Z7handleri+0x98)[0x400b05]
/lib/x86_64-linux-gnu/libc.so.6(+0x36ff0)[0x7f7c96c2fff0]
./a.out(_Z9function1v+0x10)[0x400b5d]
./a.out(_Z9function0v+0x9)[0x400b73]
./a.out(main+0x27)[0x400b9c]
/lib/x86_64-linux-gnu/libc.so.6(__libc_start_main+0xf5)[0x7f7c96c1ade5]
./a.out[0x4009a9]


Abort(Core dumped) means you, or someone you called, called the abort function and your program was abruptly terminated.
#include 

int main()
{
        std::cout << "Calling abort!\n";
        ::abort();
        std::cout << "Not reached\n";
}

paul@fasolt:~/c_test$ ./a.out
Calling abort!
Aborted (core dumped)
paul@fasolt:~/c_test$
Segmentation fault means you went somewhere you shouldn't,

No comments:

Post a Comment