我写了一个C程序如下:
案例一
int *a; /* pointer variable declaration */
int b; /* actual variable declaration */
*a=11;
a=&b;/* store address of b in pointer variable*/
运行程序时出现段错误。
我修改了如下代码:
案例2
int *a; /* pointer variable declaration */
int b; /* actual variable declaration */
a=&b;/* store address of b in pointer variable*/
*a=11;
现在它工作正常。
如果有人知道,请解释为什么在案例 1 中会出现段错误。
最佳答案
CASE .1
int *a; /* pointer variable declaration */
int b; /* actual variable declaration */
*a=11;//Not valid means you are not owner of the address where a now pointing it is unknown and accessing this will segfault/
a=&b;/* store address of b in pointer variable*/
这将是段错误,因为您使用的地址不是有效地址,并且您在那里存储的 11 是非法的。
b
+-------+ +--------+
| + | 11 |
|Unknown| | |
+---+---+ +---+----+
| |
| |
+ +
a a
CASE .2
int *a; /* pointer variable declaration */
int b; /* actual variable declaration */
a=&b;/* store address of b in pointer variable*/
*a=11;
现在它可以正常工作了,因为 b 的地址是有效的,而且你在那里存储了合法的 11。
另外上述情况也不是指针声明的正确方式
int *a = NUll;
a = malloc(sizeof(int));
*a=5;
free(a);//must
或
int *a = NUll;
int b;
a = &b;
*a=5;
这将多次消除很难发现的段错误。
关于c - 指针初始化给出段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17873561/