Skip to content

Instantly share code, notes, and snippets.

@jybaek
Last active June 24, 2016 08: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 jybaek/1e75620c51f61bfae371 to your computer and use it in GitHub Desktop.
Save jybaek/1e75620c51f61bfae371 to your computer and use it in GitHub Desktop.
backtrace와 addr2line을 이용한 디버깅 방법
#include <execinfo.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <signal.h>
/* sig ==> signal number */
void calltrace(int sig)
{
int j, nptrs;
#define SIZE 3
void *buffer[100];
char **strings;
nptrs = backtrace(buffer, SIZE);
printf("backtrace() returned %d addresses\n", nptrs);
/* The call backtrace_symbols_fd(buffer, nptrs, STDOUT_FILENO)
would produce similar output to the following: */
strings = backtrace_symbols(buffer, nptrs);
if (strings == NULL) {
perror("backtrace_symbols");
exit(EXIT_FAILURE);
}
for (j = 0; j < nptrs; j++)
printf(">>> %s\n", strings[j]);
free(strings);
exit(255);
}
void
myfunc3(void)
{
fprintf(stderr, "%s \n", __func__);
int *p = NULL;
*p = 1;
}
static void /* "static" means don't export the symbol... */
myfunc2(void)
{
fprintf(stderr, "%s \n", __func__);
myfunc3();
}
void
myfunc(int ncalls)
{
fprintf(stderr, "%s \n", __func__);
if (ncalls > 1)
myfunc(ncalls - 1);
else
myfunc2();
}
int
main(int argc, char *argv[])
{
if (argc != 2) {
fprintf(stderr, "%s num-calls\n", argv[0]);
exit(EXIT_FAILURE);
}
(void) signal (SIGSEGV, calltrace);
myfunc(atoi(argv[1]));
exit(EXIT_SUCCESS);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment