summaryrefslogtreecommitdiffstats
path: root/Tests/FindBacktrace/Test/backtrace.c
blob: 1a60b144494fbff0f6a2014b605fff96a4e76497 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
/* This is the code from `man backtrace_symbols`, reformatted, and without
 * requiring a command-line argument */

#include <execinfo.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

#define BT_BUF_SIZE 100

void myfunc3(void)
{
  int nptrs;
  void* buffer[BT_BUF_SIZE];
  char** strings;

  nptrs = backtrace(buffer, BT_BUF_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 (size_t j = 0; j < nptrs; j++)
    printf("%s\n", strings[j]);

  free(strings);
}

static void /* "static" means don't export the symbol... */
myfunc2(void)
{
  myfunc3();
}

void myfunc(int ncalls)
{
  if (ncalls > 1)
    myfunc(ncalls - 1);
  else
    myfunc2();
}

int main(int argc, char* argv[])
{
  myfunc(5);
  exit(EXIT_SUCCESS);
}