c - 指针初始化给出段错误

标签 c pointers segmentation-fault variable-assignment

我写了一个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/

相关文章:

c - ESP8266 Arduino 请求内容编码

c++ - 找不到 lopencv_core 和其他库变量

c - 将消息值转换为宏?

c++ - 链表段错误。我猜我在这里用指针做错了什么

c - 打印输出时出现段错误

c - 没有if的if语句?

c++ - 动态分配一个全局数组,该数组位于动态分配的结构数组中

c++ - 如何在c中使用struct?

c - Sprintf 段错误

c++ - 使用 strcpy 时重复出现段错误