How to automatically generate a stacktrace when a gcc C++ program crashes?

C++Server Side ProgrammingProgramming

For Linux and we can use gcc to compile C/C++ codes. This compiler uses glibc library. We can use the backtrace() function to trace the error. This function is present inside the execinfo.h header file. In this example, we are going to display Segmentation fault error using the stack trace feature.


#include <iostream>
#include <execinfo.h>
#include <signal.h>
#include <cstdlib>
#include <unistd.h>
using namespace std;
void error_handler(int sig) {
   void *array[10];
   size_t size;
   size = backtrace(array, 10); //get the void pointers for all of the entries
   cout << "Error: signal "<< sig <<":\n"; //display error signal
   backtrace_symbols_fd(array, size, STDERR_FILENO);
void invalid_index() {
   int *ptr = (int*) - 1;
   cout << *ptr << endl; // segmentation error
void func1() {
void func2() {
int main(int argc, char **argv) {
   signal(SIGSEGV, error_handler); // use handler to print the errors
   func2(); // this will call all other function to generate error


Error: signal 11:
Published on 02-May-2019 16:04:07