- 论坛徽章:
- 0
|
我写c的平台是redhat linux9.0
下面是我实验的一小段代码:
1 #include <stdio.h>
2 typedef struct
3 {
4 int stack[4];
5 int top;
6 }stack;
7 void init( stack *s)
8 {
9 s->top=-1;
10 }
11 int main()
12 {
13 int i;
14 stack *s;
15 init(s);
16 printf("%d\n",s->top);
17 s->top++;
18 s->stack[s->top]=4;
19 printf("%d\t",s->top);
20 printf("%d\n",s->stack[s->top]);
21 printf("\n");
22 }
[root@zzuli shiyan]# ./a.out
-1
0 4
如果我把第13和18行改成下面这样的话,就会出现断错误。
13 int i,x=4;
18 s->stack[s->top]=x;
gcc -g -rdynamic e.c
[root@zzuli shiyan]# ./a.out
段错误
然后我我用GDB调试结果如下:
[root@zzuli shiyan]# gdb ./a.out
GNU gdb Red Hat Linux (5.3post-0.20021129.18rh)
Copyright 2003 Free Software Foundation, Inc.
GDB is free software, covered by the GNU General Public License, and you are
welcome to change it and/or distribute copies of it under certain conditions.
Type "show copying" to see the conditions.
There is absolutely no warranty for GDB. Type "show warranty" for details.
This GDB was configured as "i386-redhat-linux-gnu"...
(gdb) r
Starting program: /c/shiyan/a.out
Program received signal SIGSEGV, Segmentation fault.
0x080485de in init (s=0x8048686) at e.c:9
9 s->top=-1;
(gdb)
显示我的9行错误了。。。
为此我又做了一个实验:
1 #include <stdio.h>
2 typedef struct
3 {
4 int data;
5 int dd;
6 }ll;
7 int main()
8 {
9 int j;
10 //i=4;
11 j=5;
12 ll *p;
13 //p->data=i;
14 p->dd=j;
15 printf("%d\n",p->dd);
16 }
运行结果是:
[root@zzuli shiyan]# ./a.out
5
如果我做一下修改
9 int i,j;//第9行加一个变量
10 //i=4;//第10行的注释去掉
13 //p->data=i;//第13行的注释去掉
15 printf("%d\t%d\n",p->dd,p->data);
之后结果结果就是断错误
[root@zzuli shiyan]# gcc -g -rdynamic ee.c
[root@zzuli shiyan]# ./a.out
段错误
GDB调试结果如下:
[root@zzuli shiyan]# gdb ./a.out
GNU gdb Red Hat Linux (5.3post-0.20021129.18rh)
Copyright 2003 Free Software Foundation, Inc.
GDB is free software, covered by the GNU General Public License, and you are
welcome to change it and/or distribute copies of it under certain conditions.
Type "show copying" to see the conditions.
There is absolutely no warranty for GDB. Type "show warranty" for details.
This GDB was configured as "i386-redhat-linux-gnu"...
(gdb) r
Starting program: /c/shiyan/a.out
Program received signal SIGSEGV, Segmentation fault.
0x080485e8 in main () at ee.c:13
13 p->data=i;
(gdb)
请大家帮我看看这些错误是怎么回事?我实在是搞不明白.我上GOOGLE上查了一些关于段错误的东西,他们说断错误大部分情况下是指针指向了不能访问的内存空间.....可是我不明白我的错误是哪里错了.......
这学期开数据结构,我在做堆栈实验的时候碰上的这种问题,自己想搞明白是怎么回事,可是一直都没有弄明白,要怪也就只能怪自己大一的时候没有学好C了...........
希望好心的朋友帮着看看.......... |
|