【发布时间】: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