【问题标题】:Segmentation fault after allocating memory for a struct in C [duplicate]为C中的结构分配内存后出现分段错误[重复]
【发布时间】:2019-12-06 09:34:11
【问题描述】:
#include <stdio.h>
#include <malloc.h>

struct node
{
    int data;
    struct node *next;
};

struct queue
{
    struct node *front;
    struct node *rear;
};

struct queue *q;

void create_queue(struct queue *);
int main()
{
    create_queue(q);

    ptr = (struct node*)malloc(sizeof(struct node));
    ptr->data = 42;

    q->front = ptr; <-- here it fails with Sementaion fault

    return 0;
}

void create_queue(struct queue *q)
{
    q = (struct queue*)malloc(sizeof(struct queue));
    q->rear = NULL;
    q->front = NULL;
}

这在尝试将 ptr 分配给队列前面时失败了,但是如果我在 create_queue(q) 之前将行 q = (struct queue*)malloc(sizeof(struct queue)); 移动到 main 函数,一切正常。 Segmentation fault错误的原因取决于代码中的内存分配位置。

【问题讨论】:

    标签: c segmentation-fault malloc


    【解决方案1】:

    您需要将双指针struct queue **q 传递给create_queue()

    void create_queue(struct queue **q)
    {
        *q = (struct queue*)malloc(sizeof(struct queue));
        (*q)->rear = NULL;
        (*q)->front = NULL;
    }
    

    这是因为您要更新指针 q 本身,而不是它指向的内容。

    【讨论】:

      【解决方案2】:

      以下函数不会更新全局变量 q。

      void create_queue(struct queue *q)
      {
          q = (struct queue*)malloc(sizeof(struct queue));
          q->rear = NULL;
          q->front = NULL;
      }
      

      它实际上是在使用超出范围的局部变量,随后出现内存泄漏(全局变量仍然指向一些垃圾)。 你需要这样定义你的函数:

      void create_queue(struct queue **q)
      {
          *q = (struct queue*)malloc(sizeof(struct queue));
          *q->rear = NULL;
          *q->front = NULL;
      }
      

      然后调用它

      create_queue(&q);
      

      所以你应该将变量的地址而不是值传递给函数。

      【讨论】:

      • 谢谢,但要编译我们还需要放置括号(*q)-&gt;rear = NULL; (*q)-&gt;front = NULL;
      • @Dmitrii 不要将所有字段设置为 NULL,只需调用 bzero(*q,sizeof(struct queue)) 或 memset()
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-08
      • 2021-08-06
      • 2018-01-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多