Chapter 6: Stacks
Introduction
Learning Outcomes
Model a stack as a list S = {a0, …, an−1} and identify its bottom and top.
Write push/pop around a top index and check for overflow and underflow.
Allocate nodes with malloc, link them, and free each node you remove.
Explain why function calls behave like a stack and why the call stack can overflow.
Choose between a fixed array, a growable array, and a linked list by cost.
Share one memory array among n stacks using top[i] and boundary[i].
The Stack ADT
The Stack: Last In, First Out
A stack is an ordered list in which all insertions and deletions happen at one end only. For S = {a0, a1, …, an−1}, a0 is the bottom and an−1 is the top. The last item in is the first one out: LIFO (last-in-first-out).
Cars parked in a one-car-wide dead end: the last one in (D) has to leave first.
Don't confuse the stack ADT with the heap data structure (Chapter 13) or with the heap memory that malloc manages.
The Stack ADT
How a Stack Grows and Shrinks
A pushed → A is now on top; top = 0.
B pushed → B is now on top; top = 1.
C pushed → C is now on top; top = 2.
D pushed → D is now on top; top = 3.
E pushed → E is now on top; top = 4.
Deletion happens only at the top: the first item removed is E, the last one added. D is on top again; top = 3.
- Push order: A, B, C, D, E.
- Pop order (if we removed them all): E, D, C, B, A, exactly reversed.
- To reach an item in the middle (say B), everything above it must be popped first.
- This restriction is not a flaw but a contract: “the last job opened is the first one closed.”
The Stack ADT
Abstract Data Type: Stack
| Operation | Meaning | Precondition / error |
|---|---|---|
stack_create(max) | Empty stack holding at most max items | — |
stack_full(S) | True if it holds max items | — |
push(S, x) | Puts x on top | Overflow if full |
stack_empty(S) | True if it holds no items | — |
pop(S) | Removes and returns the top item | Underflow if empty |
stack_top(S) · peek | Reads the top item without removing it | Error if empty |
An ADT says what the operations do, not how. The same interface can be implemented with a fixed array, a growable array, or a linked list (Horowitz–Sahni, ADT 3.1).
The Stack ADT
Where Stacks Show Up
Every function call pushes a frame holding its return address and local variables.
Compilers use a stack to convert infix to postfix and to evaluate postfix.
At a dead end in a maze, go back to the most recent fork.
Every closing bracket must match the most recently opened one.
An editor pushes every action; Ctrl+Z undoes the latest one.
DFS keeps the vertices still to visit on a stack.
The Stack ADT
push and pop Only at the Top
Push four times, then pop: items come out in reverse order. Popping an empty stack is underflow.
Array-Based Stack
Array-Based Stack: the top Index
An empty stack has top = −1. Popping from it is an underflow error.
Pushing onto it is an overflow error.
Mixing the two up is the classic off-by-one bug.
C does not check array bounds: an unchecked push overwrites neighboring memory.
Array-Based Stack
Array-Based Stack: C Definitions
#include <stdio.h> #include <stdlib.h> #define MAX_STACK_SIZE 101 typedef struct { int key; /* other fields */ } element; element stack[MAX_STACK_SIZE]; void stack_full(void) { printf("Stack is full!!!\n"); exit(-1); } void stack_empty(void) { printf("Stack is empty!!!\n"); exit(-2); }
element: the record stored on the stack; for now its only field iskey.- The stack is a global array;
topis passed in by address from the caller. - The error routines print a message and end the program with
exit.
Array-Based Stack
Push and Pop Routines
void push(int *top, element item) { if (*top >= MAX_STACK_SIZE - 1) /* any room? */ stack_full(); /* warn and exit */ stack[++*top] = item; /* bump the index first */ } /* then store the item */ element pop(int *top) { if (*top < 0) stack_empty(); /* warn and exit if empty */ return stack[(*top)--]; /* return, then decrement */ }
stack[++*top]*top is incremented first, then the item is written at the new index: on an empty stack, −1 → 0.
stack[(*top)--]The item at the old index is read first, then *top is decremented. The parentheses matter: *top-- would decrement the pointer itself.
Array-Based Stack
A Precedence Trap in C: * with ++/--
| Expression | How C parses it | Result |
|---|---|---|
++*top | ++(*top): increment the int it points to | Correct (push) |
(*top)-- | use the int it points to, then decrement it | Correct (pop) |
*top-- | *(top--): decrement the pointer, read the old address | Wrong: top is unchanged |
*top++ | *(top++): advance the pointer | Wrong |
Postfix ++/-- binds tighter than unary *; prefix ++ and * share a level and associate right to left.
top belongs to the caller; we pass &top so the routine can change it (C passes arguments by value).
Array-Based Stack · Run the code step by step
Code Trace: Array-Based Stack
In main, top = −1 (empty). Push A, B, C; pop; push D, E, F. MAX_STACK_SIZE = 4.
-1 ≥ 3? No, there is room.
++*top → top = 0, then stack[0] = A.
0 ≥ 3? No, there is room.
++*top → top = 1, then stack[1] = B.
1 ≥ 3? No, there is room.
++*top → top = 2, then stack[2] = C.
2 < 0? No, the stack is not empty.
stack[2] = C is returned, then top = 1. The old value stays in the cell, but it is no longer part of the stack.
1 ≥ 3? No, there is room.
++*top → top = 2, then stack[2] = D.
2 ≥ 3? No, there is room.
++*top → top = 3, then stack[3] = E.
3 ≥ 3? Yes: no room left!
stack_full() prints a message and ends the whole program with exit(-1). That is a heavy-handed reaction for library code; a version that returns bool leaves the decision to the caller.
void push(int *top, element item) { if (*top >= MAX_STACK_SIZE - 1) stack_full(); /* "Stack is full!!!", exit */ stack[++*top] = item; } element pop(int *top) { if (*top < 0) stack_empty(); /* "Stack is empty!!!", exit */ return stack[(*top)--]; }
Array-Based Stack
Better Design: the Stack as an Object
#include <stdbool.h> #define CAP 100 typedef struct { int data[CAP]; int top; /* -1 when empty */ } Stack; void stack_init(Stack *s) { s->top = -1; } bool stack_empty(const Stack *s) { return s->top < 0; } bool stack_full(const Stack *s) { return s->top == CAP - 1; } int stack_size(const Stack *s) { return s->top + 1; } bool stack_top(const Stack *s, int *x) { if (stack_empty(s)) return false; *x = s->data[s->top]; return true; }
- The array and
toplive in one struct, so two stacks can coexist in a program without interfering. - No globals: every routine takes the stack as a parameter.
- On error the routine returns
falseinstead of callingexit; the caller decides what to do.
Array-Based Stack · Run the code step by step
Code Trace: push / pop Returning bool
After stack_init(&s), top = −1. Push 5, 8, 2, 9, then pop four times. CAP = 3.
-1 == 2? No, there is room.
++s->top → 0; data[0] = 5; returns true.
0 == 2? No, there is room.
++s->top → 1; data[1] = 8; returns true.
1 == 2? No, there is room.
++s->top → 2; data[2] = 2; returns true.
top == CAP − 1 (2 == 2) → return false. The program keeps running; the caller learns about the overflow.
Not empty; *x = data[2] = 2, then top = 1.
Not empty; *x = data[1] = 8, then top = 0.
Not empty; *x = data[0] = 5, then top = -1.
top < 0 → return false: underflow, and *x is left untouched.
bool push(Stack *s, int x) { if (s->top == CAP - 1) return false; /* overflow */ s->data[++s->top] = x; return true; } bool pop(Stack *s, int *x) { if (s->top < 0) return false; /* underflow */ *x = s->data[s->top--]; return true; }
Array-Based Stack
Write It as a Component: stack.h and stack.c
/* stack.h: all the client sees */ #ifndef STACK_H #define STACK_H #include <stdbool.h> typedef struct Stack Stack; /* opaque */ Stack *stack_create(int capacity); void stack_destroy(Stack *s); bool push(Stack *s, int x); bool pop(Stack *s, int *x); bool stack_empty(const Stack *s); #endif
Client code cannot see inside the struct; it only calls the operations. Even if the implementation switches from an array to a linked list, client code stays the same.
/* stack.c: implementation */ struct Stack { int *data; int top, cap; }; Stack *stack_create(int cap) { Stack *s = malloc(sizeof *s); if (s == NULL) return NULL; s->data = malloc(cap * sizeof *s->data); if (s->data == NULL) { free(s); return NULL; } s->top = -1; s->cap = cap; return s; } void stack_destroy(Stack *s) { if (s) { free(s->data); free(s); } }
Array-Based Stack · Run the code step by step
Code Trace: Reversing a String with a Stack
Input "VISIT"; an empty stack is set up.
s[0] = 'V' ≠ '\0' → push('V').
s[1] = 'I' ≠ '\0' → push('I').
s[2] = 'S' ≠ '\0' → push('S').
s[3] = 'I' ≠ '\0' → push('I').
s[4] = 'T' ≠ '\0' → push('T').
pop → 'T', s[0] = 'T'.
pop → 'I', s[1] = 'I'.
pop → 'S', s[2] = 'S'.
pop → 'I', s[3] = 'I'.
pop → 'V', s[4] = 'V'.
The stack is empty: pop returns false and the loop ends. Result: "TISIV". n pushes + n pops → O(n).
void reverse(char *s) { Stack st; int c, i; stack_init(&st); for (i = 0; s[i] != '\0'; i++) push(&st, s[i]); /* assume CAP suffices */ for (i = 0; pop(&st, &c); i++) s[i] = (char)c; }
Linked Stack
Implementing a Stack with a Linked List
A, B, C pushed in that order: top points to the head of the list.
- Each item is a node:
dataplus alinkto the next node. - Insert and delete at the head: both O(1), no shifting.
- No capacity limit: overflow happens only if
mallocfails.
Linked Stack · Run the code step by step
Code Trace: Linked push
Start: node *top = NULL; (empty stack). Push 10, 20, 30 in turn.
malloc allocates a new node; if it is not NULL we continue. Its fields are still undefined.
new_node->data = 10.
new_node->link = *top: the new node points to the old top (NULL). Order matters: link first, then change *top.
*top = new_node: the caller's top now points to 10. Stack: 10.
malloc allocates a new node; if it is not NULL we continue. Its fields are still undefined.
new_node->data = 20.
new_node->link = *top: the new node points to the old top (node(10)). Order matters: link first, then change *top.
*top = new_node: the caller's top now points to 20. Stack: 20 → 10.
malloc allocates a new node; if it is not NULL we continue. Its fields are still undefined.
new_node->data = 30.
new_node->link = *top: the new node points to the old top (node(20)). Order matters: link first, then change *top.
*top = new_node: the caller's top now points to 30. Stack: 30 → 20 → 10.
After three pushes: 30 → 20 → 10 → NULL. Each push does a constant amount of work: O(1).
bool push(node **top, int x) { node *new_node = malloc(sizeof *new_node); if (new_node == NULL) return false; /* no memory */ new_node->data = x; new_node->link = *top; /* point to old top */ *top = new_node; /* new top */ return true; }
Linked Stack · Run the code step by step
Code Trace: Linked pop
Stack: 30 → 20 → 10. We call pop four times; main prints each successful result.
old = *top: just a copy of a pointer; no new memory is allocated.
*x = 30 (read the value before the node is freed).
*top = old->link → node(20).
free(old): node 30's memory goes back to the system. main prints 30.
old = *top: just a copy of a pointer; no new memory is allocated.
*x = 20 (read the value before the node is freed).
*top = old->link → node(10).
free(old): node 20's memory goes back to the system. main prints 20.
old = *top: just a copy of a pointer; no new memory is allocated.
*x = 10 (read the value before the node is freed).
*top = old->link → NULL.
free(old): node 10's memory goes back to the system. main prints 10.
old = NULL → the stack is empty, return false. The loop stops here.
bool pop(node **top, int *x) { node *old = *top; /* no malloc! */ if (old == NULL) return false; /* empty */ *x = old->data; *top = old->link; /* advance top */ free(old); /* release memory */ return true; }
Linked Stack
Who Owns the Memory in a Linked Stack
typedef struct node { int data; struct node *link; } node; void stack_clear(node **top) { while (*top != NULL) { node *old = *top; *top = old->link; free(old); } } /* afterwards *top == NULL */
oldis a pointer variable, not a new node: it needs nomalloc.- Save the link first (
*top = old->link), then callfree: the other way round reads freed memory. - Call
stack_clearbefore the program ends: everymallocneeds a matchingfree.
Linked Stack
Array-Based or Linked?
| Criterion | Fixed array | Growable array | Linked list |
|---|---|---|---|
| Capacity | Fixed at compile time | ×2 as needed | Until memory runs out |
| push / pop | O(1) | O(1) amortized | O(1), a malloc per push |
| Extra memory per item | None | None (except unused capacity) | One pointer (8 bytes) |
| Cache behavior | Very good | Very good | Poor (nodes scattered) |
| Overflow | Possible | Only if realloc fails | Only if malloc fails |
| Bug risk | Bounds checks | realloc's return value | forgotten free, dangling pointer |
If the maximum size is known, use a fixed array; if not, a growable array is usually fastest in practice. A linked stack suits cases where the nodes already live in other structures or are created and destroyed one at a time.
The Call Stack
The Call Stack Overflows Too
The call stack is a stack: each call pushes a frame holding the return address, parameters, and locals, and return pops it. The most recently called function finishes first.
Recursion with no base case, or one it never reaches, pushes a frame per call; when the system stack (typically a few MB) fills up, the program crashes with a stack overflow.
A local array such as int a[1000000]; lives in the frame and can overflow the stack on its own. Put large data on the heap with malloc.
return &local; is a bug: once the frame is popped, other calls reuse that memory (a dangling pointer).
Any recursive algorithm can be turned into a loop that maintains its own stack.
Multiple Stacks
Multiple Stacks: Start with Two
- Stack 1 grows up from 0, stack 2 grows down from m−1.
- Empty:
top1 = −1,top2 = m. - Full:
top1 + 1 == top2, when the two meet.
Multiple Stacks · Run the code step by step
Code Trace: n Stacks, One Memory
MEM = 12, n = 3: 4 cells each; top[i] = boundary[i] = (m/n)·i − 1, boundary[n] = m − 1.
Room; memory[0] = 5, top[0] = 0.
Room; memory[4] = 7, top[1] = 4.
Room; memory[1] = 9, top[0] = 1.
Room; memory[8] = 4, top[2] = 8.
Room; memory[2] = 2, top[0] = 2.
Room; memory[3] = 8, top[0] = 3.
top[0] == boundary[1] (3 == 3) → stack 0 is full, yet 6 cells are free! Horowitz's stack_full would shift stacks.
top[1] ≠ boundary[1] → not empty; *x = 7, top[1] = 3.
/* stack i: boundary[i]+1 .. boundary[i+1] */ bool push(int i, int x) { if (top[i] == boundary[i+1]) return false; /* full */ memory[++top[i]] = x; return true; } bool pop(int i, int *x) { if (top[i] == boundary[i]) return false; /* empty */ *x = memory[top[i]--]; return true; }
Multiple Stacks
Sharing Memory Among n Stacks: Pros and Cons
A one-dimensional array (memory[MEMORY_SIZE]) can be split into n segments to hold n stacks; each stack's top and boundary values are kept in two auxiliary arrays.
Pros
- One
malloc, one array: easy to manage. - push/pop are still O(1).
- The same idea works for queues (n queues).
Cons
- When one segment fills, you get a “full” error even if memory has room elsewhere.
- Shifting stacks to make room costs O(m): shifting is expensive.
- Segment sizes are hard to predict in advance.
stack_full(i) looks for free space first to the right, then to the left, and shifts the stacks in between by one cell. In the worst case every push can cost O(m).Lab · C code step by step
Lab: Linked Stack
Summary
Which Output Orders Are Possible?
We push 1, 2, 3, 4 in this order and may pop any number of times in between. Which of the output orders below can we get?
| Output order | Possible? |
|---|---|
1 2 3 4 | showYes: pop right after each push. |
4 3 2 1 | showYes: four pushes, then four pops. |
2 4 3 1 | showYes: push1 push2 pop(2) push3 push4 pop(4) pop(3) pop(1). |
3 1 4 2 | showNo: when 3 comes out, 1 and 2 are on the stack with 2 on top, so 1 cannot come out before 2. |
General rule: after some x is output, the items pushed before x and not yet popped must come out in reverse order. The number of possible orders for n items is a Catalan number (14 for n = 4).
Summary
Complexity Summary
| Operation | Fixed array | Growable array | Linked |
|---|---|---|---|
| push | O(1) | O(1) amortized, O(n) worst case | O(1) |
| pop | O(1) | O(1) | O(1) |
| peek / empty / full | O(1) | O(1) | O(1) |
| Memory for n items | MAX (fixed) | ≤ 2n | n · (item + pointer) |
| Cleanup | O(1) | O(1) (one free) | O(n) |
| fact(n) call stack | O(n) frames (whatever the implementation) | ||
| Multiple-stack push | O(1); making room O(m) | — | — |
Summary
Common Mistakes
*top--: it decrements the pointer; the correct form is (*top)--.top with the item count (count = top + 1).*top = new_node first and losing the old list.free, or never freeing the node.malloc for a temporary pointer that doesn't need it, and leaking memory.Summary
Exercises
- Make the array stack's
pushreturnboolinstead of callingexit. - Write
push(k, x)andpop(k)for two stacks in one array (k = 1, 2). - Wrap the linked stack in a
structholdingtopand asizefield. - Write
void reverse(char *s): reverse a string with a stack. - With only push/pop, return a stack's bottom item (a helper stack is allowed).
- At most how many frames are on the stack during
fact(5)? Draw them withmain.
Hints / answers
- On overflow
return false;, otherwisestack[++*top] = item; return true;. - Empty: top1 = −1, top2 = m. Full: top1 + 1 == top2. For k = 2, push uses
--top2and pop usestop2++. typedef struct { node *top; int size; } LinkedStack;; ++size on push, --size on a successful pop.- Push the characters, then pop them back into the array: O(n) time, O(n) extra memory.
- Move all to the helper stack, keep the last, move them back: O(n).
- fact(5), fact(4), …, fact(1) + main = 6 frames.
Summary
Chapter Summary
Insert and delete only at the top; last in, first out.
top = −1 empty, top = MAX − 1 full; ++*top and (*top)--.
Return a status instead of calling exit; the caller decides about overflow/underflow.
top = head of list; push/pop O(1); free every node you pop.
Each call is a frame: return address, locals, previous frame.
One memory, top[i] and boundary[i]; a full segment forces shifting.
Summary
References and Next Steps
- E. Horowitz, S. Sahni, S. Anderson-Freed, Fundamentals of Data Structures in C, 2nd ed., Sections 3.1–3.2, 3.7, and 4.3.
- T. H. Cormen et al., Introduction to Algorithms, 3rd ed., Section 10.1 (stacks) and Chapter 17 (amortized analysis).
- R. Sedgewick, Algorithms in C, Parts 1–4, Chapter 4.