4

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

2 に答える 2

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 */
}
于 2012-11-26T21:25:26.560 に答える
1

私の最善の推測はそれです

queue->tail

インスタンス化されません。

于 2012-11-26T21:24:37.523 に答える