- In Gnu libc:
the array to contain the return addresses returned by
backtraceis allocated on the stack. Therefore code like this can be used in
situations where the memory handling via
malloc does not workanymore (in which case the
backtrace_symbols has to be replacedby a
backtrace_symbols_fd call as well). The number of returnaddresses is normally not very large. Even complicated programs rather
seldom have a nesting level of more than, say, 50 and with 200 possible
entries probably all programs should be covered.
#include <execinfo.h>
#include <stdio.h>
#include <stdlib.h>
/* Obtain a backtrace and print it to stdout. */
void
print_trace (void)
{
void *array[10];
size_t size;
char **strings;
size_t i;
size = backtrace (array, 10);
strings = backtrace_symbols (array, size);
printf ("Obtained %zd stack frames.\n", size);
for (i = 0; i < size; i++)
printf ("%s\n", strings[i]);
free (strings);
}
/* A dummy function to make the backtrace more interesting. */
void
dummy_function (void)
{
print_trace ();
}
int
main (void)
{
dummy_function ();
return 0;
}
- In Java:
for (StackTraceElement e:stack) {
... ...
}
or in hotspot VM:
sun.reflect.Reflection.getCallerClass (1)