簡體   English   中英

分段故障問題。 嘗試在C中實現雙鏈表FIFO隊列

[英]Segmentation-fault Issue. Trying to implement a Doubly Linked List FIFO Queue in C

我在使用此代碼時遇到麻煩。 我是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){

在這一行中,您檢查fifo元素head的地址。 這可能不是您想要的。 相反,您要檢查指針的值是否有效:

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

沒有實例化。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM