c - Why my code crashes if I call push function more than 8 times? -
// whenever increasing function phone call times of force more 8, crashed before working good. help required. in below code have created programme stack using dynamic array keeping in mind there should not stack overflow using realloc function doubling values whenever stack gets filled.
#include<stdio.h> #include<stdlib.h> #include<memory.h> typedef struct arraystack { int top; int capacity; int *arr; }*stack; stack creation() { stack s; s=(stack)malloc(sizeof(struct arraystack)); if(!s)return null; s->top=-1; s->capacity=1; s->arr=(int*)malloc(s->capacity*sizeof(int)); if(!s->arr)return null; homecoming s; } int is_full(stack s) { homecoming s->top==s->capacity-1; } int is_empty(stack s) { homecoming s->top==-1; } void doubling(stack s) { s->capacity*=2; s->arr=realloc(s->arr,s->capacity); } void push(stack s,int data) { if(is_full(s)) doubling(s); s->arr[++s->top]=data; } int pop(stack s) { if(is_empty(s)) printf("\nstack underflow"); else homecoming s->arr[s->top--]; } int main() { stack s; int i=0,size=9; s=creation(); **for(i=0;i<size;i++) push(s,19+1);** // in case homecoming 0; }
s->arr = malloc(s->capacity * sizeof(int)); s->arr = realloc(s->arr, s->capacity);
you reallocate plenty space s->capacity / sizeof(int)
items.
c stack stack-overflow
No comments:
Post a Comment