abhay  jain
abhay jain

Reputation: 156

unknown coding error in implementation of queue using linked list

Following is my implementation of queue using linked list.I am totally new to data structures and was trying to implement queue data structure .This code compiles successfully but as soon as i try to run it ,the program crashes.I dont have any idea how to solve this issue.If you guys have any clue, what's wrong with my code, please give me an idea.

Thanks for any help.

Here is my C Code :

#include<stdio.h>
#include<stdlib.h>
#define null 0
typedef struct node//node of a linked list
{
    int info;//info part of node
    struct node* next;// next pointer of a node
}*nodeptr;
typedef struct queue
{
    nodeptr front;//front pointer of a queue
    nodeptr rear;//rear pointer of a queue
} *QUEUE;

int empty_queue(QUEUE qwe)//if queue is empty then return 1
{
    if (qwe->front==null)
    return 1;
    else
    return 0;
}
void insert_queue( QUEUE qwe,int x)
{
    nodeptr p=(nodeptr)malloc(sizeof(struct node));//allocate new memory space to be added to queue
    p->next=null;
    p->info=x;
    if(empty_queue(qwe))//if the queue is empty,front and rear point to the new node
    {
    qwe->rear=p;
    qwe->front=p;
    return; 

    }
    qwe->rear->next=p;
    qwe->rear=p;
    //rear points to the new node
    return; 
}
int delete_queue(QUEUE qwe)
{   
    int x;
    if(empty_queue(qwe))//if queue is empty then it is the condition for underflow
    {
        printf("underflow\n");
        return;
    }
    nodeptr p=qwe->front;//p points to node to be deleted
    x=p->info;//x is the info to be returned
    qwe->front=p->next;
    if(qwe->front==null)//if the single element present was deleted
    qwe->rear=null;
    free(p);
    return x;

}
int main()
{
    int a;
    QUEUE qwe;
    qwe->rear=null;
    qwe->front=null;
    printf("enter values to be enqueued and -1 to exit\n");
    while(1)
    {
        scanf("%d",&a);
        if(a==-1)
        break;
        insert_queue(qwe,a);
    }
    printf("the values you added to queue are\n");
    while(!empty_queue(qwe))
    printf("%d\n",delete_queue(qwe));
    return 0;


}

Upvotes: 2

Views: 408

Answers (1)

simonc
simonc

Reputation: 42165

QUEUE qwe; declares a pointer to uninitialised memory. You need to allocate memory for the queue, either on the stack

struct queue qwe
qwe.rear=null;

or dynamically on the heap

QUEUE qwe = malloc(sizeof(*qwe));
qwe->rear=null;
...
free(qwe); /* each call to malloc requires a corresponding free */

Its quite easy to introduce this type of buf when you hide a pointer behind a typedef. Another solution would be to change QUEUE to be of type struct queue. You'd then be much more likely to notice any uninitialised pointers in your code.

Upvotes: 4

Related Questions