使用backtrace打印函数调用堆栈
#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;
size_t i;
size = backtrace (array, 10);
printf ("Obtained %zd stack frames./n", size);
for (i = 0; i < size; i++)
printf("%p\n", array [i]);
}
/* A dummy function to make the backtrace more interesting. */
void dummy_function (void)
{
print_trace ();
}
int main (void)
{
dummy_function ();
return 0;
}
编译执行代码
$ gcc -g main.c && ./a.out 1000 100 2
Obtained 5 stack frames./n0x558405050722
0x558405050796
0x5584050507a2
0x7f73e75fac87
0x55840505061a
通过addr2line -e a.out 0x55fa948a9858
命令定位到调用位置。在某些系统中直接打印的不是真实地址,这样不能直接得出调用位置,此时可以使用gdb工具,使用如下:
$ gdb ./a.out
(gdb) run
Starting program: /home/cooper/tool/malloc_hook/a.out
Obtained 5 stack frames./n0x555555554722
0x555555554796
0x5555555547a2
0x7ffff7a03c87
0x55555555461a
[Inferior 1 (process 20187) exited normally]
(gdb)
(gdb)
(gdb) l*0x555555554796
0x555555554796 is in dummy_function (main.c:22).
17 /* A dummy function to make the backtrace more interesting. */
18
19 void dummy_function (void)
20 {
21 print_trace ();
22 }
23
24 int main (void)
25 {
26 dummy_function ();
参考:https://blog.51cto.com/u_4080467/1743978