Chinaunix
标题:
程序错误退出的调试
[打印本页]
作者:
大隐隐于床
时间:
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
欢迎光临 Chinaunix (http://bbs.chinaunix.net/)
Powered by Discuz! X3.2