Reputation: 245
I wrote this program to build a queue.
#include <stdio.h>
#include <stdlib.h>
typedef struct Queue{
int *array;
int front,rear,size,capacity;
}Queue;
int isFull(Queue *q){
return q->size == q->capacity;
}
int isEmpty(Queue *q){
return q->size == 0;
}
Queue *createQueue(int capacity){
Queue *q = (Queue *)malloc(sizeof(Queue));
q->size = 0;
q->front = 0;
q->capacity = capacity;
q->rear = capacity - 1;
q->array = (int *)malloc(sizeof(int)*capacity);
}
void enqueue(Queue *q,int num){
if(isFull(q))
return;
q->rear = (q->rear + 1) % q->capacity;
q->array[q->rear] = num;
q->size++;
}
int dequeue(Queue *q){
int item;
if(isEmpty(q))
return -1;
item = q->array[q->front];
q->front = (q->front + 1) % q->capacity;
q->size--;
return item;
}
int main(void) {
Queue *q = createQueue(10);
enqueue(q,1);
enqueue(q,2);
enqueue(q,3);
enqueue(q,4);
printf("%d ",dequeue(q));
printf("%d ",dequeue(q));
printf("%d ",dequeue(q));
printf("%d ",dequeue(q));
return 0;
}
Program works perfectly fine when run from Linux terminal. When I run the same program in ideone.com I am getting a runtime error.
I did try to find memory leaks in the program manually. There seems to be no problem
Why is this happening?
Upvotes: 0
Views: 166
Reputation: 2608
Queue *createQueue(int capacity){
Queue *q = (Queue *)malloc(sizeof(Queue));
q->size = 0;
q->front = 0;
q->capacity = capacity;
q->rear = capacity - 1;
q->array = (int *)malloc(sizeof(int)*capacity);
return q;
}
Upvotes: 0
Reputation: 3725
Your function createQueue
is supposed to return a pointer to a Queue
but there's no explicit return
in it: what is returned by your function is not guaranted across compiler/platforms.
This type of error is catched by gcc with warnings turned on (-Wall
).
Upvotes: 1