Hardik Malhotra
Hardik Malhotra

Reputation: 114

What's wrong in this queue implementation?

following is my queue implementation. My queue is simply an array of two qnodes: head and rear. enqueue and dequeue are supposed to handle the internal queue implementation.

The output to Q[0].next == Q[1].next is coming 1 after I call enqueue with different integers. I am unable to figure out the mistake.

struct Qnode{
int index;
struct Qnode *next;
};
typedef struct Qnode qnode;

qnode* makeQueue(){
     qnode *Q;
     Q = (qnode *) malloc(2*sizeof(qnode));
     qnode head,tail;
     head.next = NULL;
     tail.next = NULL;
     head.index = 0;
     tail.index = -1;
     Q[0] = head;
     Q[1] = tail;
     return Q;
}

void enQueue(qnode *Q, int index){
    qnode node,head = Q[0], rear = Q[1];
    node.index = index;
    node.next = NULL;
    if(head.next == NULL && rear.next == NULL){
        head.next = &node;
        rear.next = &node;
    }
    else{
        (rear.next)->next = &node;
        rear.next = &node;
    }
    Q[0].index = head.index + 1;
}

Thanks

Upvotes: 2

Views: 120

Answers (1)

LPs
LPs

Reputation: 16223

You have a problem into enQueue function

qnode node,head = Q[0], rear = Q[1];
node.index = index;
node.next = NULL;
if(head.next == NULL && rear.next == NULL){
    head.next = &node;
    rear.next = &node;
}

The piece of code above is assigning to head.next and rear.next the address of a local scoped variable: i.e. stack allocated variable.

node variable will only exists until the function ends. So the address into those pointers aren't valid outside the function: accessing it outside function is illegal and Undefined Behavior

Moreover all modifications done into that function are not reflected to Q array: you are modifying local scoped copy of array elements.

Upvotes: 0

Related Questions