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);
}
대개 이미 할당 한 데이터에 한계를 기록합니다. [Valgrind] (http://valgrind.org/)와 같은 도구를 사용하여 찾을 수 있습니다. –
디버거를 사용하고 많은 코드를 덤프하지 마십시오 –
'Q q; q = malloc (sizeof (Q));'typedef는 유해한 것으로 간주됩니다. – wildplasser