Linux程序异常退出打印调用堆栈

转自:https://blog.csdn.net/adream307/article/details/43574945

/* 
 * 程序异常终止时打印异常程序调用堆栈 
 * gcc -g -rdynamic BackTraceTest.c -o BackTraceTest 
 * 
 * 运行程序出现错误: 
 * System error, Stack trace: 
 * 0 ./BackTraceTest(SystemErrorHandler+0x77) [0x40095b] 
 * 1 /lib64/libc.so.6() [0x3a4fe326b0] 
 * 2 ./BackTraceTest(Fun1+0x10) [0x400a10] 
 * 3 ./BackTraceTest(Fun+0xe) [0x400a23] 
 * 4 ./BackTraceTest(main+0x37) [0x400a5c] 
 * 5 /lib64/libc.so.6(__libc_start_main+0xfd) [0x3a4fe1ed5d] 
 * 6 ./BackTraceTest() [0x400829] 
 * Segmentation fault (core dumped) 
 * 
 * gdb打印错误行信息 
 * gdb BackTraceTest 
 * (gdb) info line *0x400a10 
 * Line 66 of "BackTraceTest.c" starts at address 0x400a0c <Fun1+12> and ends at 0x400a13 <Fun1+19>. 
 * (gdb) list *0x400a10 
 * 0x400a10 is in Fun1 (BackTraceTest.c:66). 
 * warning: Source file is more recent than executable. 
 * 61   } 
 * 62 
 * 63   void Fun1() 
 * 64   { 
 * 65       char *p=NULL; 
 * 66       *p = 'A'; 
 * 67   } 
 * 68 
 * 69   void Fun() 
 * 70   { 
 * 
 * 
 * addr2line 定位程序地址对应的源代码位置 
 * addr2line  -e BackTraceTest -i 0x400a10 
 * /home/cyf/workspace/BackTraceTest/BackTraceTest.c:66 
 * 
 */  
#include<stdio.h>  
#include<stdlib.h>  
#include<signal.h>  
#include<string.h>  
#include<execinfo.h>  
  
void SystemErrorHandler(int signum)  
{  
    const int len=1024;  
    void *func[len];  
    size_t size;  
    int i;  
    char **funs;  
  
    signal(signum,SIG_DFL);  
    size=backtrace(func,len);  
    funs=(char**)backtrace_symbols(func,size);  
    fprintf(stderr,"System error, Stack trace:\n");  
    for(i=0;i<size;++i) fprintf(stderr,"%d %s \n",i,funs[i]);  
    free(funs);  
    //exit(1);  
}  
  
void Fun1()  
{  
    char *p=NULL;  
    *p = 'A';  
}  
  
void Fun()  
{  
    Fun1();  
}  
  
int main(const int argc,const char* argv[])  
{  
    signal(SIGSEGV,SystemErrorHandler); //Invaild memory address  
    signal(SIGABRT,SystemErrorHandler); // Abort signal  
    Fun();  
    return 0;  
}  

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值