Listing 12 Implements stacks on the heap

/* stack3.c */

#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include "stack3.h"

Stack *stack_create(int size)
{
   Stack *stkp;

   if ((stkp =
       malloc(sizeof(Stack))) ==
       NULL)
      return NULL;
   if ((stkp->data =
      calloc(size, sizeof(int))) ==
      NULL)
   {
      free(stkp);
      return NULL;
   }

   stkp->size = size;
   stkp->ptr = 0;
   return stkp;
}

int stack_push(Stack *stkp, int x)
{
   assert(stkp);
   return (stkp->ptr < stkp->size)
     ? (stkp->data[stkp->ptr++] = x)
     : STACK_ERROR;
}

int stack_pop(Stack *stkp)
{
   assert(stkp);
   return (stkp->ptr > 0)
     ? stkp->data[--stkp->ptr]
     : STACK_ERROR;
}

void stack_destroy(Stack *stkp)
{
   assert(stkp);
   free(stkp->data);
   free(stkp);
}

/* End of File */