0

I am inserting element in queue but an infinite loop is running //x is the element to be entered

 void enqueue(int x)
  {
   queue *ptr;
   ptr=(queue*)malloc(sizeof(queue));
   ptr->info=x;
   if(front==NULL&&rear==NULL)
   {
      front=rear=ptr;
      ptr->next=NULL;
   }
   else
   {
    rear->next=ptr;
    rear=ptr;
   }
 }

//Show function to print the elements

  void show()
  {
  queue *ptr=front;
  while(ptr!=NULL)
    {
      printf("%d\n",ptr->info);
      ptr=ptr->next;
    }
  }
Dumb
  • 43
  • 1
  • 1
  • 9
  • Standard Warning : Please [do not cast](http://stackoverflow.com/q/605845/2173917) the return value of `malloc()` and family in `C`. – Sourav Ghosh Apr 06 '15 at 11:45
  • There is a conflict between cast and do not cast in the above discussion so which one to follow – Dumb Apr 06 '15 at 11:57

2 Answers2

1

You need to add ptr->next=NULL which in your case is set inside the if loop. It should be set in both conditions

 void enqueue(int x)
  {
   queue *ptr;
   ptr=malloc(sizeof(queue)); // As sourav mentioned you don't need to cast here
   ptr->info=x;
   ptr->next=NULL;
   if(front==NULL&&rear==NULL)
   {
      front=rear=ptr;
      //ptr->next=NULL;
   }
   else
   {
    rear->next=ptr;
    rear=ptr;
   }
 }
Srinath Mandava
  • 3,384
  • 2
  • 24
  • 37
  • 2
    Standard Warning Repeat : Please [do not cast](http://stackoverflow.com/q/605845/2173917) the return value of `malloc()` and family in `C`. – Sourav Ghosh Apr 06 '15 at 11:44
0

You're only setting ptr->next to NULL in one of your cases, you should be doing it for both (or outside the if statement altogether):

void enqueue(int x) {
    queue *ptr = malloc (sizeof (*ptr));

    // should really check for NULL here first

    ptr->info = x;
    ptr->next = NULL;

    // If front is NULL, rear should be as well,
    // so only need check one.

    if (front == NULL) {
        front = rear = ptr;
    } else {
        rear->next = ptr;
        rear = ptr;
    }
}

You'll notice a couple of other things I've fixed, specifically:

  • Removing the casting of the return value of malloc, which can be dangerous.
  • Shortening the code where possible.
  • Removing redundant checks like head and tail pointers.
  • Suggesting you check all operations which can fail, especially if they're likely to cause catastrophic effects like malloc may.
paxdiablo
  • 854,327
  • 234
  • 1,573
  • 1,953