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

#include 

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)

留着备用吧

你可能感兴趣的:(基本编程,c语言,linux,开发语言)