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>
#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");
}
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