I am having trouble 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 am unable to perform this operation without getting a segmentation fault:
queue->tail->next = temp;
I can’t seem to come up with a solution or a work around to not use this line of code. Can anyone help explain why this line of code will not work? Thanks in advance.
Also, here is the fifo and fifo_element structure:
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
In this line you check the address of the element
headin yourfifo. This is probably not what you want. Instead, you want to check whether the value of your pointer is valid:Also keep in mind that you have to initiate the fifo with the correct values:
And you should check whether malloc actually returns a valid address: