为什么这个程序在这个队列程序中给出分段错误

Why this program gives segmention fault in this queue program

这是队列的C程序。我刚刚为插入值编写了它。我遇到的问题是每当我插入第一个元素时都会出现分段错误。

#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 *);
struct queue *insert(struct queue *,int);

int main()
{

int val, option;
create_queue(q);

do
{

printf("\n *****MAIN MENU*****");       
printf("\n 1. INSERT");     
printf("\n Enter your option : ");
scanf("%d", &option);

switch(option)
        {
            case 1:             
                                printf("\n Enter the number to insert in the queue:");
                scanf("%d", &val);
                q = insert(q,val);
                break;

        }

}while(option != 5);

return 0;
}

void create_queue(struct queue *q)
{
    q = (struct queue *)malloc(sizeof(struct queue));
    q->rear = NULL;//how this happened without any error??
    q->front = NULL;
}

struct queue *insert(struct queue *q,int val)
{

struct node *ptr;

ptr = (struct node*)malloc(sizeof(struct node));
if(ptr == NULL)
{
    printf("error in allocating\n");
    return -1;
}
    ptr->data = val;
    if(q->front == NULL)
    {
        q->front = ptr;//here I get segmentation fault
        q->rear = ptr;
        q->front->next = q->rear->next = NULL;
    }
    else
    {
        q->rear->next = ptr;
        q->rear = ptr;
        q->rear->next = NULL;
    }

return q;
}

我的程序有什么问题? 为什么新节点的赋值不起作用,目前的语法是什么?

这里的问题是,当您使用全局变量调用函数并在函数参数中接受该函数参数时,函数参数成为被调用函数的局部参数。

这样一来,局部变量就覆盖了全局变量,并且由于 C 使用按值传递函数参数传递,因此对本地副本所做的任何更改都不会反映到调用者。

最后,全局指针p保持未初始化状态。尝试取消引用导致 undefined behavior.

你要么

  • 不需要将全局变量作为参数传递
  • 传递指针的地址并在函数内部对其进行操作。

也就是说,please see this discussion on why not to cast the return value of malloc() and family in C.