分段故障问题.试图在C中实现双链表FIFO队列

use*_*560 4 c malloc pointers segmentation-fault

我在使用此代码时遇到问题.我是C的新手,据我所知,我正在使用malloc操作.

#include "fifo.h"
#include <stdlib.h>

/* add a new element to a fifo */
void Enqueue( fifo* queue, int customerId)
{
   //allocate memory for the element being added
   //initialize fifo_element
   fifo_element *temp;
   temp = (fifo_element*)malloc(sizeof(fifo_element));
   temp->customerId = customerId;
   temp->prev = NULL;
   temp->next = NULL;

   //if the queue is empty, add the element to the start
   if(&queue->head == NULL){
      queue->head = queue->tail = temp;
      return;
   }
   else{
      queue->tail->next = temp;
      temp->prev = queue->tail;
      queue->tail = temp;
      return;      
   }   
}
Run Code Online (Sandbox Code Playgroud)

如果没有出现分段错误,我无法执行此操作:

queue->tail->next = temp;
Run Code Online (Sandbox Code Playgroud)

我似乎无法提出解决方案或解决不使用这一行代码的问题.任何人都可以帮助解释为什么这行代码不起作用?提前致谢.

另外,这里是fifo和fifo_element结构:

struct fifo_element
{
   int customerId;
   fifo_element *next;
   fifo_element *prev;
};

struct fifo
{
   fifo_element *head;
   fifo_element *tail;
};
Run Code Online (Sandbox Code Playgroud)

这是我入口时的电话:

Enqueue( &f, i ); //f is of type fifo
Run Code Online (Sandbox Code Playgroud)

Zet*_*eta 5

if(&queue->head == NULL){
Run Code Online (Sandbox Code Playgroud)

在此行中,检查元素的地址head在你的fifo.这可能不是你想要的.相反,您要检查指针的值是否有效:

if(queue->head == NULL){
Run Code Online (Sandbox Code Playgroud)

另请注意,您必须使用正确的值启动fifo:

fifo f;
f.head = 0;
f.tail = 0;
Enqueue( &f, 1 );
Run Code Online (Sandbox Code Playgroud)

你应该检查malloc是否实际返回一个有效的地址:

temp = (fifo_element*)malloc(sizeof(fifo_element));
if(temp == NULL){
     /* insufficient memory, print error message, return error, etc */
} else {
     /* your code */
}
Run Code Online (Sandbox Code Playgroud)