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

时间:2012-11-26 21:20:51

标签: c pointers segmentation-fault malloc

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

2 个答案:

答案 0 :(得分:5)

if(&queue->head == NULL){

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

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 */
}

答案 1 :(得分:1)

我最好的猜测是

queue->tail

未实例化。