指针初始化导致分段错误 [英] Pointer initialisation gives segmentation fault
问题描述
我写了一个C程序如下:
I wrote a C program as follows:
int *a; /* pointer variable declaration */
int b; /* actual variable declaration */
*a=11;
a=&b;/* store address of b in pointer variable*/
运行程序时出现分段错误.
It gives a segmentation fault when running the program.
我把代码改成如下:
int *a; /* pointer variable declaration */
int b; /* actual variable declaration */
a=&b;/* store address of b in pointer variable*/
*a=11;
现在一切正常.
如果有人知道,请解释为什么它在 CASE 1 中给出了分段错误.
If anyone knows please explain why it is giving a segmentation fault in CASE 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 是非法的.
This is going to be segmentation fault because the address you are using is not a valid address and there you are storing 11 which is illegal.
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 是合法的.
Now its working fine because the address of b is valid an there you are storing 11 which is legal.
上述情况也不是正确的指针声明方式
Also above cases are not correct way of pointer declaration
int *a = NUll;
a = malloc(sizeof(int));
*a=5;
free(a);//must
或
int *a = NUll;
int b;
a = &b;
*a=5;
这将消除多次难以找到的分段错误.
This will remove segmentation fault many times which is hard to find .
这篇关于指针初始化导致分段错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!