Segmentation error. Attempting to implement a double linked list FIFO queue in C

I am having problems with this code. I am new to C, and as far as I can tell, I am using the malloc operation correctly.

#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; } } 

I cannot perform this operation without receiving a segmentation error:

 queue->tail->next = temp; 

I can’t come up with a solution or work not to use this line of code. Can someone explain why this line of code is not working? Thanks in advance.

In addition, the fifo and fifo_element structure are presented here:

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

and here is my call when Enqueuing:

 Enqueue( &f, i ); //f is of type fifo 
+4
source share
2 answers
 if(&queue->head == NULL){ 

On this line, you check the address of the head element in fifo . This is probably not what you want. Instead, you want to check if your pointer value is valid:

 if(queue->head == NULL){ 

Also keep in mind that you must initiate fifo with the correct values:

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

And you should check if malloc really returns a valid address:

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

My best guess is that

 queue->tail 

not created.

+1
source

All Articles