title: Implementing Stack using Dynamic Array
body: <p>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.</p>
  
  <pre><code>#include &lt;stdio.h&gt;
  #include &lt;stdlib.h&gt;
  
  struct Stack {
      int *arr;
      int top,size,capacity;
  };
  
  struct Stack *createStack(int capacity) {
      struct Stack *s = (struct Stack*)malloc(sizeof(struct Stack));
      s-&gt;arr = (int*)malloc(sizeof(int)*capacity);
      s-&gt;top = -1;
      s-&gt;capacity = capacity;
      s-&gt;size = 0;
      return s;
  }
  
  void doubleStack(struct Stack *s) {
      s-&gt;capacity = s-&gt;capacity*2;
      s-&gt;arr = realloc(s-&gt;arr,s-&gt;capacity);
      printf("Array doubling happened successfully!\n");
  }
  
  int isFull(struct Stack *s) {
      return s-&gt;size == s-&gt;capacity;
  }
  
  void push(struct Stack *s, int item) {
      if(isFull(s))
          doubleStack(s);
  
      printf("%d pushed!\n",item);
      s-&gt;arr[++(s-&gt;top)] = item;
      s-&gt;size++;
  }
  
  int isEmpty(struct Stack *s) {
      return s-&gt;size == 0;
  }
  
  void pop(struct Stack *s) {
      if(isEmpty(s)) {
          printf("Empty stack!\n");
          return;
      }
  
      int item = s-&gt;arr[(s-&gt;top)--];
      s-&gt;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;
  }
  </code></pre>