Obtaining a backtrace from a program
The following program should be compiled with -rdynamic
:
//
// https://github.com/soarpenguin/code-sample-c/blob/master/backtrace.c
//
#include <execinfo.h>
#include <stdio.h>
#include <stdlib.h>
void backtr() {
void *callstack[128];
int nofsymbols = backtrace(callstack, 128);
char **symbols = backtrace_symbols(callstack, nofsymbols);
for (int i = 0; i < nofsymbols; ++i) {
printf("%s\n", symbols[i]);
}
free(symbols);
}
void func_D() { backtr(); }
void func_C() { func_D(); }
static void func_B() { func_C(); } //The name of func_B is not exposed because it is static.
void func_A() { func_B(); }
int main() { func_A(); }
The program prints something like
./prog(backtr+0x1f) [0x563568ad6188]
./prog(func_D+0xe) [0x563568ad61f4]
./prog(func_C+0xe) [0x563568ad6205]
./prog(+0x1216) [0x563568ad6216]
./prog(func_A+0xe) [0x563568ad6227]
./prog(main+0xe) [0x563568ad6238]
/lib/x86_64-linux-gnu/libc.so.6(+0x2724a) [0x7f690547024a]
/lib/x86_64-linux-gnu/libc.so.6(__libc_start_main+0x85) [0x7f6905470305]
./prog(_start+0x21) [0x563568ad60a1]