backtrace

使用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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值