定义指针时要进行初始化这是大家都知道的事, 用malloc一般情况都可以保证在堆上分配空间,使指针指向这里;然后我就想,通过gdb跟踪找到malloc开辟出来的空间地址,那么这个地址的空间是肯定可以被读取和写入的,那么下回我自己进行赋值,而不用malloc,这样不也可以保证正常运行吗?但还是段错误。。。。。这是两次gdb跟踪的对比。 我分析时哪里出了问题?
(gdb) b 8
Breakpoint 1 at 0x804842d: file 2.c, line 8.
(gdb) run
Starting program: /media/D_S_BIRD/src/Segment_fault/2
Breakpoint 1, main (argc=1, argv=0xbffff494) at 2.c:10
10 *p = 'x';
(gdb) display p
1: p = 0x804b008 "" 此时p= 0x804b008
(gdb) display *p
2: *p = 0 '/000' *p = 0
(gdb) s
11 printf("%c/n", *p);
2: *p = 120 'x' *p = 'x'正常赋值
1: p = 0x804b008 "x"
(gdb) s
x
12 return 0;
2: *p = 120 'x'
1: p = 0x804b008 "x"
(gdb) s
13 }
2: *p = 120 'x'
1: p = 0x804b008 "x"
(gdb) q
Breakpoint 1, main (argc=1, argv=0xbffff494) at 2.c:8
8 int *p = 0x804b008;
(gdb) display p
1: p = (int *) 0x26eff4
(gdb) display *p
2: *p = 1314172
(gdb) s
10 *p = 'x';
Disabling display 2 to avoid infinite recursion.
2: *p = Cannot access memory at address 0x804b008 为什么在这个0x804b008的地址里面就不能存'x'?