1

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?

4
  • 1
    Please use a debugger. What is q->tail? What happens with the first node that you add to the queue? Commented Oct 19, 2018 at 4:45
  • q->tail->next = newNode;: Here Priority_queue q; you allocated the 1st node, here Qnode *newNode = malloc(sizeof(Qnode)); you allocated the 3rd node. Where and when is the 2nd allocated? Commented Oct 19, 2018 at 4:55
  • Read How to debug small programs Commented Oct 19, 2018 at 5:04
  • q->tail is initialised to NULL and you want to access q->tail->next..... That's the problem! You can change the value of q->tail first before looking at q->tail->next Commented Oct 19, 2018 at 6:36

1 Answer 1

5

In your code, init() initializes q->tail with NULL. And you are trying to do q->tail->next = newNode. In case of first node it will essentially means NULL->next = newNode. This is the reason of segmentation fault.

Your enqueue() should be like :

void enqueue(Priority_queue *const q, const char new_element[], int priority) {

    /*......*/

    Qnode *newNode = (Qnode*) malloc(sizeof(Qnode));
    if (q->tail) {                /*Do this, only When first node is already allocated*/
        q->tail->next = newNode; 
    }
    q->tail = newNode; 

    /*.......*/

}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.