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

C语言中打印函数的调用栈,第1张

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%0lxn", i, address[i]);
//      这个函数获取的栈字符不准,不用也罢
//      symbols = backtrace_symbols(address, n);     
//      for (int i = 0; i < n; i++)
//              printf("#%d: x/i 0x%0lx %sn", 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 :    mov    %eax,-0xc(%rbp)
(gdb) x/i 0x40078c
   0x40078c :   mov    $0x1388,%edi
(gdb) x/i 0x4007c9
   0x4007c9 :  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 
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:
...
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 :    mov    %eax,-0xc(%rbp)
(gdb) x/i 0x40078c
   0x40078c :   mov    $0x1388,%edi
(gdb) x/i 0x4007c9
   0x4007c9 :  mov    $0x4008c4,%edi
(gdb) x/i 0x7fbdfa920495
   0x7fbdfa920495 <__libc_start_main+245>:      mov    %eax,%edi
(gdb) x/i 0x4005d9
   0x4005d9 <_start+41>:        hlt
(gdb)

留着备用吧

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5714459.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-17
下一篇 2022-12-18

发表评论

登录后才能评论

评论列表(0条)

保存