このコードに問題があります。私は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