6/27/12

How to print a stack trace in your user space linux application

When debugging some code I wanted to print out the stack trace of code allocating/deallocating memory without using gdb. I run over the eminent article at: http://www.linuxjournal.com/article/6391 that explained how to use the functions backtrace() and backtrace_symbols() in glibc. Read the article at Linuxjournal if you want more information, copy the code from this page if you only want a function that you can use.

A short summary:

Compile the program with:
gcc -g -rdynamic stack_trace.c -o stack_trace

Test program:
#include <stdio.h>
#include <stdlib.h>
#include <execinfo.h>

void stack_trace(){
  void *trace[16];
  char **messages = (char **)NULL;
  int i, trace_size = 0;

  trace_size = backtrace(trace, 16);
  messages = backtrace_symbols(trace, trace_size);
  printf("[stack trace]>>>\n");
  for (i=0; i < trace_size; i++)
    printf("%s\n", messages[i]);
  printf("<<<[stack trace]\n");

  free(messages);
}

void main(){
  stack_trace();
}


When running it produces the following output:
[stack trace]>>>
./stack_trace(stack_trace+0x27) [0x804861b]
./stack_trace(main+0xb) [0x8048680]
/lib/libc.so.6(__libc_start_main+0xe7) [0xbeece7]
./stack_trace() [0x8048561]
<<<[stack trace]

If you want to find the exact location of the adress last on stack:[0x804861b].
Use addr2line:
~/code_examples$ addr2line 0x804861b -e stack_trace
/home/kungjohan/code_examples/stack_trace.c:13

No comments:

Post a Comment