2009年8月20日星期四
对段错误调试文章的补遗和更正
[chen@localhost seg]$ cat -n backtrace2.c
1 #include <stdio.h>
2 #include <execinfo.h>
3 #include <stdlib.h>
4 #include <signal.h>
5
6 /*
7 * A dummy function to make the backtrace more interesting.
8 */
9 void
10 dummy_function(void)
11 {
12 unsigned char *ptr = 0x00;
13 *ptr = 0x00;
14 }
15
16 void myfunc3(void)
17 {
18 dummy_function();
19 }
20
21 void myfunc2(void)
22 {
23 myfunc3();
24 }
25
26 void myfunc(int n)
27 {
28 if (n > 1)
29 myfunc(n-1);
30 else
31 myfunc2();
32 }
33
34 void dump(int signo)
35 {
36 void *array[10];
37 size_t size;
38 char **strings;
39 size_t i;
40
41 size = backtrace(array, 10);
42 strings = backtrace_symbols(array,size);
43
44 printf("Obtained %zd stack frames.\n", size);
45
46
47 for ( i = 0; i < size ; ++i )
48 printf("%s\n",strings[i]);
49
50 free(strings);
51 exit(0);
52 }
53
54 int
55 main(void)
56 {
57 signal(SIGSEGV, &dump);
58
59 myfunc(3);
60
61 return 0;
62 }
g++ -g -rdynamic backtrace2.c -o backtrace2
[chen@localhost seg]$ ./backtrace2
Obtained 10 stack frames.
./backtrace2(_Z4dumpi+0x19) [0x804889b]
[0xa65420]
./backtrace2(_Z14dummy_functionv+0x10) [0x8048804]
./backtrace2(_Z7myfunc3v+0x8) [0x8048812]
./backtrace2(_Z7myfunc2v+0x8) [0x804881c]
./backtrace2(_Z6myfunci+0x21) [0x804883f]
./backtrace2(_Z6myfunci+0x1a) [0x8048838]
./backtrace2(_Z6myfunci+0x1a) [0x8048838]
./backtrace2(main+0x31) [0x8048873]
/lib/libc.so.6(__libc_start_main+0xdc) [0x3e1dec]
objdump -d -S backtrace2
080487f4 <_Z14dummy_functionv>:
/*
* A dummy function to make the backtrace more interesting.
*/
void
dummy_function(void)
80487f4: 55 push %ebp
80487f5: 89 e5 mov %esp,%ebp
80487f7: 83 ec 10 sub $0x10,%esp
{
unsigned char *ptr = 0x00;
80487fa: c7 45 fc 00 00 00 00 movl $0x0,0xfffffffc(%ebp)
*ptr = 0x00;
8048801: 8b 45 fc mov 0xfffffffc(%ebp),%eax
8048804: c6 00 00 movb $0x0,(%eax)
}
8048807: c9 leave
8048808: c3 ret
8048809: 90 nop
上述例子说明我之前发布的内容是错误的,通过objdump是可以判断到具体哪一行代码出现段错误。
真是太好了!再次赞叹GNU组织开发出的glibc
订阅:
博文评论 (Atom)
没有评论:
发表评论