Created
March 31, 2014 06:06
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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(" [email protected]\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