Overflow happens when you push onto a full stack; underflow when you pop an empty one. Both indicate a bug or bad input and must be detected, not ignored. Separately, a call-stack overflow occurs when recursion goes too deep, typically from a missing base case; the operating system aborts the program.
Remember
if (top == CAP - 1) return OVERFLOW;
if (top == -1) return UNDERFLOW;
Reference
Cheat Sheet
Keep these facts handy while you work with Stack Overflow and Underflow in C.
Topic
Detail
Overflow
Push on full
Underflow
Pop on empty
Handling
Return a status or error code
Call stack
Missing base case in recursion
Code
C Examples
Compile each example with gcc file.c -std=c11 -Wall -o out. Next: Expression Conversion.
Example 1 — Report both errors
A stack of capacity 2.
C
#include <stdio.h>
struct Stack { int data[2]; int top; };
static const char *push(struct Stack *s, int v) {
if (s->top == 1) return "overflow";
s->data[++s->top] = v;
return "ok";
}
static const char *pop(struct Stack *s, int *out) {
if (s->top < 0) return "underflow";
*out = s->data[s->top--];
return "ok";
}
int main(void) {
struct Stack s = {{0}, -1};
int v = 0;
printf("push 1: %s\n", push(&s, 1));
printf("push 2: %s\n", push(&s, 2));
printf("push 3: %s\n", push(&s, 3));
for (int i = 0; i < 3; i++) {
const char *r = pop(&s, &v);
if (r[0] == 'o') printf("pop: %d\n", v);
else printf("pop: %s\n", r);
}
return 0;
}
Output
push 1: ok
push 2: ok
push 3: overflow
pop: 2
pop: 1
pop: underflow
How It Works
The third push is rejected with "overflow".
Two pops succeed; the third finds the stack empty.
Returning a message string keeps the demo readable; real code usually returns an enum or int.
Edge Cases & Pitfalls
Check these before relying on Stack Overflow and Underflow in real programs.
silent
Silent failure
Ignoring the status leaves the program using stale data.
abort
Using assert in production
assert disappears with NDEBUG. Use real checks for runtime conditions.
Remember
Key Takeaways
Overflow: full push.
Underflow: empty pop.
Always check and report.
One line: Overflow happens when you push onto a full stack; underflow when you pop an empty one.
Frequently Asked Questions
Pushing onto a full stack, or exhausting the call stack through very deep or infinite recursion.
Trying to pop or peek from an empty stack.
Continue with "C Expression Conversion" next. Convert infix expressions to postfix with an operator stack. The C Stacks hub lists every topic in order.