C/C++ 程序段错误退出时输出堆栈信息

该博客介绍了如何在Linux环境中利用``库中的`backtrace_*`函数来捕获和打印程序运行时的错误堆栈信息。通过示例代码展示了当发生SIGSEGV信号时,自定义信号处理器如何获取并输出堆栈轨迹,帮助开发者定位问题所在。在编译和运行示例程序后,输出显示错误发生在`baz()`函数中。
摘要由CSDN通过智能技术生成

在 Linux 平台下可以使用 `<execinfo.h>` 里的 `backtrace_*` 函数,详见 [Backtraces](http://www.gnu.org/software/libc/manual/html_node/Backtraces.html),例子如下,

```c++

#include <stdio.h>
#include <execinfo.h>
#include <signal.h>
#include <stdlib.h>
#include <unistd.h>

void handler(int sig)
{
    void *array[10];
    size_t size;

    // get void*'s for all entries on the stack
    size = backtrace(array, 10);

    // print out all the frames to stderr
    fprintf(stderr, "Error: signal %d:\n", sig);
    backtrace_symbols_fd(array, size, STDERR_FILENO);
    exit(1);
}

void baz()
{
    int *foo = (int*)-1; // make a bad pointer
    printf("%d\n", *foo); // causes segfault
}

void bar() { baz(); }
void foo() { bar(); }

int main(int argc, char **argv)
{
  signal(SIGSEGV, handler); /// install our handler
  foo(); // this will call foo, bar, and baz.  baz segfaults.
}


```

输入 `gcc -g -rdynamic ./test.c -o test` 进行编译,接着运行就会输出如下,

```
$ ./test
Error: signal 11:
./test(handler+0x19)[0x400911]
/lib64/tls/libc.so.6[0x3a9b92e380]
./test(baz+0x14)[0x400962]
./test(bar+0xe)[0x400983]
./test(foo+0xe)[0x400993]
./test(main+0x28)[0x4009bd]
/lib64/tls/libc.so.6(__libc_start_main+0xdb)[0x3a9b91c4bb]
./test[0x40086a]
```

可以看到是在 `baz` 中出现错误。

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值