Skip to content

Instantly share code, notes, and snippets.

@rongyi
Created March 31, 2014 06:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rongyi/9886205 to your computer and use it in GitHub Desktop.
Save rongyi/9886205 to your computer and use it in GitHub Desktop.
how to print backtrace in C, remember add gcc option '-rdynamic' when compile
#include <execinfo.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <signal.h>
#include <unistd.h>
#define BACKTRACE_SIZE 256
static void
handle_segfault(int sig)
{
void *func[BACKTRACE_SIZE];
char **symb = NULL;
int size;
printf("======================================================================\n");
printf(" Segmentation fault: please post this backtrace to:\n");
printf(" rongyi@ucloud.cn\n");
printf("======================================================================\n");
size = backtrace(func, BACKTRACE_SIZE);
symb = backtrace_symbols(func, size);
char exe_name[512] = {};
readlink("/proc/self/exe", exe_name, sizeof(exe_name));
while (size > 0) {
const char *symbol = symb[size - 1];
char foo[1024];
printf("%d: [%s]\n", size, symbol);
if (strstr(symbol, "[0x")) {
char *p = strstr(symbol, "[0x") + 1;
char *pp = strchr(p, ']');
snprintf(foo, sizeof(foo), "addr2line -p -i -f -e %s %.*s",
exe_name,
(unsigned)(pp-p),
p);
if (system(foo) == -1)
printf("(addr2line missing)\n");
}
size --;
}
exit(1);
return;
}
int main()
{
signal(SIGSEGV, handle_segfault);
char *c = NULL;
*c = 'c';
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment