I'm trying to create a priority queue linked list, but keep running into segmentation fault.
My structure definitions are below
typedef struct node {
char *new_element;
struct node *next;
int priority;
} Qnode;
typedef struct {
Qnode *top;
Qnode *tail;
int size;
} Priority_queue;
int main() {
Priority_queue q;
init(&q);
enqueue(&q, "hi", 1);
return 0;
}
void init(Priority_queue *const q) {
q->top = NULL;
q->tail = NULL;
q->size = 0;
return 0;
}
And my enqueue method where the error is caused below
void enqueue(Priority_queue *const q, const char new_element[], int priority) {
/*......*/
Qnode *newNode = (Qnode*) malloc(sizeof(Qnode));
q->tail->next = newNode; /*causes segmentation fault*/
q->tail = newNode; /*doesn't cause segmentation fault*/
/*.......*/
}
I'm guessing I'm not dynamically allocating my memory correctly, but the way my function is written, I'm pointing from one struct to the next so is there a way to fix this?
q->tail? What happens with the first node that you add to the queue?q->tail->next = newNode;: HerePriority_queue q;you allocated the 1st node, hereQnode *newNode = malloc(sizeof(Qnode));you allocated the 3rd node. Where and when is the 2nd allocated?q->tailis initialised toNULLand you want to accessq->tail->next..... That's the problem! You can change the value ofq->tailfirst before looking atq->tail->next