I have implemented a Stack using dynamic array(implementing array doubling) but when the doubling happens for the second time, I am getting runtime error! What's going wrong with the implementation? Please help.
#include <stdio.h>
#include <stdlib.h>
struct Stack {
int *arr;
int top,size,capacity;
};
struct Stack *createStack(int capacity) {
struct Stack *s = (struct Stack*)malloc(sizeof(struct Stack));
s->arr = (int*)malloc(sizeof(int)*capacity);
s->top = -1;
s->capacity = capacity;
s->size = 0;
return s;
}
void doubleStack(struct Stack *s) {
s->capacity = s->capacity*2;
s->arr = realloc(s->arr,s->capacity);
printf("Array doubling happened successfully!\n");
}
int isFull(struct Stack *s) {
return s->size == s->capacity;
}
void push(struct Stack *s, int item) {
if(isFull(s))
doubleStack(s);
printf("%d pushed!\n",item);
s->arr[++(s->top)] = item;
s->size++;
}
int isEmpty(struct Stack *s) {
return s->size == 0;
}
void pop(struct Stack *s) {
if(isEmpty(s)) {
printf("Empty stack!\n");
return;
}
int item = s->arr[(s->top)--];
s->size--;
printf("%d popped!\n",item);
}
int main(void) {
struct Stack *s = createStack(2);
push(s,1);
push(s,2);
push(s,3);
push(s,4);
push(s,5);
pop(s);
pop(s);
return 0;
}