分段错误问题.尝试在 C 语言中实现双向链表 FIFO 队列



我在这段代码上遇到了问题。我是 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;      
   }   
}

我无法在不出现分段错误的情况下执行此操作:

queue->tail->next = temp;

我似乎无法想出不使用这行代码的解决方案或解决方法。谁能帮助解释为什么这行代码不起作用?提前谢谢。

此外,以下是 fifo 和 fifo_element 结构:

struct fifo_element
{
   int customerId;
   fifo_element *next;
   fifo_element *prev;
};
struct fifo
{
   fifo_element *head;
   fifo_element *tail;
};

这是我排队时的电话:

Enqueue( &f, i ); //f is of type fifo
if(&queue->head == NULL){

在此行中,您将检查fifohead元素的地址。这可能不是您想要的。相反,您需要检查指针的值是否有效:

if(queue->head == NULL){

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

fifo f;
f.head = 0;
f.tail = 0;
Enqueue( &f, 1 );

您应该检查 malloc 是否真的返回了一个有效的地址:

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

我最好的猜测是

queue->tail

未实例化。

最新更新