指针初始化会产生分段错误 [英] 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;
现在一切正常.
如果有人知道,请解释为什么在案例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屋!