0
#include<stdio.h>
#include<stdlib.h>
#define SIZE 5

struct CircularQueue{
  int front,rear;
  int capacity;
  int *data;
};

typedef struct CircularQueue * Q;

// create  queue
Q createQueue(int size)
{
  Q q;
  q = malloc(sizeof(Q));
  if(!q)
    return NULL;
  q->front=q->rear=-1;
  q->capacity=size;
  q->data=malloc(sizeof(int)*q->capacity);  
  if(!q->data)
    return NULL;
  printf("Queue created successfully...\n");
  return q;
}

// Resize Queue (Here it is showing error in realloc )    
void resize(Q q)
{
  int size = q->capacity;
  q->capacity *=2;  

   // *****Error 
  q->data = realloc(q->data,sizeof(int)*q->capacity);
  // *****

  if(!q->data)
  {
    printf("memory error ...\n");
    return ;
  }
  if(q->front>q->rear)
  {
    int i;
    for(i=0;i<q->front;i++)
      q->data[i+size]=q->data[i];
    q->rear = q->rear+size;  
  }

} 

// Insert in Queue

void Enqueue(Q q,int data)
{
  if(IsQueueFull(q))
    resize(q);
  if(q->front==-1)
     q->front = q->rear=0;
  else
     q->rear = (q->rear+1)  % q->capacity;  
  q->data[q->rear]=data; 
}

int IsQueueFull(Q q)
{
  return (q->rear+1)%q->capacity==q->front;
}

int IsQueueEmpty(Q q)
{
  return q->front==-1;
}

// Delete from queue

int Dequeue(Q q)
{
  if(IsQueueEmpty(q)){
    printf("Queue is empty..\n");
    return -1;
  }
  int data = q->data[q->front];
  if(q->front==q->rear)
    q->front=q->rear=-1;
  else  
    q->front = (q->front+1)%q->capacity;
  return data;
}

void display(Q q)
{
  int i;
  printf("Queue Elements :\n");
  while(!IsQueueEmpty(q))
  {
    printf("%d ",Dequeue(q));
  }
  printf("\n");
}

void main()
{
  int data;
  Q q;
  q = createQueue(SIZE);
  printf("Data : %d\n",Dequeue(q));
  Enqueue(q,10);
  Enqueue(q,20);  
  Enqueue(q,30);
  Enqueue(q,99);
  printf("Data : %d\n",Dequeue(q));
  printf("Data : %d\n",Dequeue(q));    
  Enqueue(q,2);
  Enqueue(q,9);
  Enqueue(q,19);
  Enqueue(q,29);
  display(q);
}
Alexander Vogt
  • 17,879
  • 13
  • 52
  • 68
user1587676
  • 1
  • 1
  • 1

1 Answers1

1

When you do sizeof(Q) in e.g. the line

q = malloc(sizeof(Q));

You actually only allocate size for a pointer, i.e. sizeof(struct CircularQueue *). This is only four or 8 bytes depending on platform (32 or 64 bits).

The actual size of the structure is 21 or 20 bytes (16 bytes plus padding) depending on 32 or 64 bit platform.

This leads to you writing beyond the allocated memory and you then have undefined behavior. What is most likely happening is that you overwrite data needed by the memory allocation system, so the realloc call later will fail rather catastrophically.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621