免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 866 | 回复: 0
打印 上一主题 下一主题

程序错误退出的调试 [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2009-05-21 16:23 |只看该作者 |倒序浏览
程序出现SIGSEGV、SIGABRT、SIGBUS等等错误时,都会默认退出。
这个时候一般用两种方法来调试最为快捷:

1 gdb调试core文件,这种方法最简单,只简单描述一下。
  1) 在编译时加入-g参数
  2) ulimit -c unlimited
  这样在程序段错语时会生成core文件
  3) gdb ./a.out 载入程序
  4) core-file core 载入core文件
  
  用backtrace或bt 查看栈信息
  用frame N 移动到指定帧,查看具体信息

2 但有的时候无法生成core文件,或者core文件无法查看到栈信息,那就要用到以下方法。
  1)在程序内加入信号响应函数,函数的作用是退出时打印栈信息。以下是示例程序:
  

#include "stdlib.h"
#include "stdio.h"
#include "signal.h"
#include "execinfo.h"
void fun_dump()
{
        void *stack_p[10];
        char **stack_info;
        int size;
        size = backtrace( stack_p, sizeof(stack_p));
        stack_info = backtrace_symbols( stack_p, size);
        printf ("%d stack frames.\n", size);
        int i = 0;
        for( ; i  size; i++)
                printf ("%s\n", stack_info);
        free( stack_info);
        exit(0);
}
int fun_err()
{
        char *p = 0x0 ;
        *p = 'a';
}
int main( int argc, char *argv[])
{
        signal( SIGSEGV, fun_dump);
        fun_err( );
}
   2) 反汇编程序,并生成文件dump
objdump -d ./a.out >> dump
   3) 编译运行,程序报错
BTC:/home/code/test # gcc -g main.c
BTC:/home/code/test # ./a.out
5 stack frames.
./a.out [0x804852d]
[0xffffe420]
./a.out [0x80485d6]
/lib/libc.so.6(__libc_start_main+0xdc) [0xb7e6587c]
./a.out [0x8048491]
  4) 查看报错信息
    【./a.out [0x804852d]】 在栈顶,是信号响应函数,不用管。
    注意【./a.out [0x80485d6]】并在dump文件中查找80485d6这个地址:
080485ac main>:
80485ac: 8d 4c 24 04 lea 0x4(%esp),%ecx
80485b0: 83 e4 f0 and $0xfffffff0,%esp
80485b3: ff 71 fc pushl 0xfffffffc(%ecx)
80485b6: 55 push %ebp
80485b7: 89 e5 mov %esp,%ebp
80485b9: 51 push %ecx
80485ba: 83 ec 14 sub $0x14,%esp
80485bd: c7 44 24 04 14 85 04 movl $0x8048514,0x4(%esp)
80485c4: 08
80485c5: c7 04 24 0b 00 00 00 movl $0xb,(%esp)
80485cc: e8 0f fe ff ff call 80483e0 signal@plt>
80485d1: e8 c1 ff ff ff call 8048597 fun_err>
80485d6: 83 c4 14 add $0x14,%esp
注意最后两行。这就是出错的函数。




本文来自ChinaUnix博客,如果查看原文请点:http://blog.chinaunix.net/u3/91335/showart_1934694.html
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP