Jul 11, 2009

How to get stack trace of a function

In Java,
try {
throw new Exception();
} catch (Exception ex) {
ex.printStackTrace();
}

In C++, we'll use backtrace function as following (note: the backtrace does not exist in uClibc so that if you want to use, you must patch the library to enable it)

#include <execinfo.h>
#include <stdio.h>
#include <stdlib.h>
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);
}


Or we can use sigsegv as followin http://www.tlug.org.za/wiki/index.php/Obtaining_a_stack_trace_in_C_upon_SIGSEGV

No comments: