C语言中打印函数的调用栈

#include <execinfo.h>

void bt()
{
        void *address[32];
        char **symbols;
        int n;
        n = backtrace(address, 32);

        for (int i = 0; i < n; i++)
        		// x/i 是为了方便gdb获取地址
                printf("#%d: x/i 0x%0lx\n", i, address[i]);
//      这个函数获取的栈字符不准,不用也罢
//      symbols = backtrace_symbols(address, n);     
//      for (int i = 0; i < n; i++)
//              printf("#%d: x/i 0x%0lx %s\n", i, address[i], symbols[i]);
}

gcc -g bt.c -std=c99 编译后,执行a.out,会打印出调用栈的地址:
#0: x/i 0x4006bc
#1: x/i 0x40078c
#2: x/i 0x4007c9
#3: x/i 0x7fb82a7fc495
#4: x/i 0x4005d9

gdb attach进程后,打印调用栈:

(gdb) x/i 0x4006bc
   0x4006bc <bt+31>:    mov    %eax,-0xc(%rbp)
(gdb) x/i 0x40078c
   0x40078c <memory_leak+48>:   mov    $0x1388,%edi
(gdb) x/i 0x4007c9
   0x4007c9 <main+24>:  mov    $0x4008c4,%edi
(gdb) x/i 0x7fb82a7fc495
   0x7fb82a7fc495 <__libc_start_main+245>:      mov    %eax,%edi
(gdb) x/i 0x4005d9
   0x4005d9 <_start+41>:        hlt

也可以在coredump文件中,用打印的信息解析:

Segmentation fault (core dumped)
[root@11 backtarce]# ls
a.out  memory-leak.c
[root@11 backtarce]# cp /tmp/core_38233_38233_a.out_11_1643055636 .
[root@11 backtarce]# gdb a.out core_38233_38233_a.out_11_1643055636
GNU gdb (GDB) Red Hat Enterprise Linux 7.6.1-114.el7
Copyright (C) 2013 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.  Type "show copying"
and "show warranty" for details.
This GDB was configured as "x86_64-redhat-linux-gnu".
For bug reporting instructions, please see:
<http://www.gnu.org/software/gdb/bugs/>...
Reading symbols from /root/C_test/backtarce/a.out...done.
[New LWP 38233]
Core was generated by `./a.out'.
Program terminated with signal 11, Segmentation fault.
#0  0x00007fbdfa9c2f90 in __nanosleep_nocancel () from /lib64/libc.so.6
Missing separate debuginfos, use: debuginfo-install glibc-2.17-260.el7_6.6.x86_64
(gdb) x/i 0x4006bc
   0x4006bc <bt+31>:    mov    %eax,-0xc(%rbp)
(gdb) x/i 0x40078c
   0x40078c <memory_leak+48>:   mov    $0x1388,%edi
(gdb) x/i 0x4007c9
   0x4007c9 <main+24>:  mov    $0x4008c4,%edi
(gdb) x/i 0x7fbdfa920495
   0x7fbdfa920495 <__libc_start_main+245>:      mov    %eax,%edi
(gdb) x/i 0x4005d9
   0x4005d9 <_start+41>:        hlt
(gdb)

留着备用吧

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值