#include #include #include #include /* Simple stack data structure. */ typedef struct sstack_t { size_t esize; /* Size of each item. */ int capacity; /* Number of items that can be stored. */ int size; /* Number of items currently in stack. */ uint8_t *data; /* Data for items. */ } sstack_t; /* Create a new stack. When done, the returned pointer should be free'd. */ static sstack_t *sstack_new(size_t esize, int capacity){ sstack_t *s = malloc(sizeof(sstack_t) + esize * capacity); if(NULL == s)return NULL; s->esize = esize; s->capacity = capacity; s->size = 0; s->data = ((uint8_t *)s) + sizeof(sstack_t); return s; } /* Push an item onto the stack. The item will be copied into the stack. * Returns 0 on success, -1 on error (overflow). */ static int sstack_push(sstack_t *stack, void *item){ if(stack == NULL || item == NULL)return -1; if(stack->size >= stack->capacity)return -1; memmove(stack->data + stack->size * stack->esize, item, stack->esize); stack->size++; return 0; } /* Pop an item from the stack, copying it into the provided buffer. * Returns 0 on success, -1 on error (underflow). * On error, the buffer is not modified. */ static int sstack_pop(sstack_t *stack, void *item){ if(stack == NULL || item == NULL)return -1; if(stack->size == 0)return -1; memmove(item, stack->data + (stack->size-1) * stack->esize, stack->esize); stack->size--; return 0; } int main(){ sstack_t *s; int items = 10000; s = sstack_new(sizeof(int), items); for(int i=0;i= 0; i--){ int p; if(sstack_pop(s, &p)){ printf("error: -1 returned at item %d\n", i); return 0; } if(p != i){ printf("error: %d returned when %d expected\n", p, i); return 0; } } free(s); return 0; }