/* stack3.c , by beck@bofh.ucs.ualberta.ca * This is a dynamically extending integer stack implemented using * an array and realloc, instead of using a linked list of * integers (a - la stack2.c). This will be much faster * than stack2.c in general, because it preserves locality * of reference and makes far fewer calls to allocate memory. */ #include #include #include "stack.h" static int STACK_SIZE = 0; static int* contents = NULL; static int top = 0; void make_empty(void) { top = 0; } int is_empty(void) { return top == 0; } static int is_full(void) { return top == STACK_SIZE; } void push(int i) { if (is_full()) { /* remember, STACK_SIZE starts as 0, and the stack contents are NULL. * - read the man page for realloc, when realloc is called with * a NULL pointer as it's first argument, it behaves just like malloc(). * so this one piece of code will both allocate my initial memory, and * will make it bigger when I fill up. */ int * tmp; STACK_SIZE += 1024; tmp = realloc (contents, (STACK_SIZE * sizeof(int))); /*C++ tmp = (int *) realloc (contents, (STACK_SIZE * sizeof(int))); */ if (tmp == NULL) { printf("Error in push: stack is full.\n"); exit(EXIT_FAILURE); } else { contents = tmp; } } contents[top++] = i; } int pop(void) { if (is_empty()) { printf("Error in pop: stack is empty.\n"); exit(EXIT_FAILURE); } return contents[--top]; }