title: Free the stack implemented in C
body: <p>I implement a stack and its functions in C. Now after all the functions were called, I wanted to free the stack.</p>
  
  <p>My question is should I free the base pointer of stack "st" first or just directly free the stack "st"? Both seems work in my code.</p>
  
  <pre><code>#include &lt;stdio.h&gt;
  #include &lt;stdlib.h&gt;
  
  #define init_size 10
  #define increment 1
  
  typedef struct sqStack
  {
      int* top;
      int* base;
      int stack_size;
  }sqStack;
  
  int init_stack(sqStack* sq)
  {
      if(sq-&gt;base==NULL)
      {
         sq-&gt;base = (int*)malloc(init_size*sizeof(int));
      }
      if(sq-&gt;base==NULL) exit(-1);
      sq-&gt;stack_size=init_size;
      sq-&gt;top=sq-&gt;base;
      return 1;
  }
  int push(sqStack* sq, int e)
  {
      if(sq==NULL) exit(-1);
  
      if(sq-&gt;top-sq-&gt;base==sq-&gt;stack_size-1)//pointer top reaches the top of the stack
      {
          int* q = (int*)realloc(sq-&gt;base,(sq-&gt;stack_size+increment)*sizeof(int));
          if(q==NULL)  exit(-1);
              sq-&gt;base=q;
          sq-&gt;top=sq-&gt;base+sq-&gt;stack_size-1;
              sq-&gt;stack_size += increment;
  
      }
      *sq-&gt;top++=e;
      return 1;
  }
  int pop(sqStack* sq,int* e)
  {
      if(sq==NULL) exit(-1);
      if(sq-&gt;base==sq-&gt;top)  exit(-1);
      sq-&gt;top--;
      *e=*sq-&gt;top;
      sq-&gt;stack_size--;
      return *e;
  }
  int top(sqStack* sq,int* e)
  {
      if(sq==NULL) exit(-1);
      if(sq-&gt;base==sq-&gt;top)  exit(-1);
      *e=*(sq-&gt;top-1);
      return *e;
  }
  int empty(sqStack* sq)
  {
      if(sq-&gt;base==sq-&gt;top) return 1;
      else return 0;
  }
  
  int main() {
      sqStack* st= (sqStack*)calloc(1,sizeof(sqStack))  ;
      int e;
      init_stack(st);
      for(int i=0;i&lt;12;i++)
      {
          push(st,i+1);
  
      }
      for(int i=0;i&lt;12;i++)
      {
          printf("%d\n",top(st,&amp;e));
          printf("%d\n",pop(st,&amp;e));
      }
      free(st-&gt;base);
      free(st);
      return 0;
  }
  </code></pre>
  
  <p>The result is:
  12
  12
  11
  11
  10
  10
  9
  9
  8
  8
  7
  7
  6
  6
  5
  5
  4
  4
  3
  3
  2
  2
  1
  1
  each number locates on a single line.</p>