How to Fix Stack Underflow and Empty Stack Pop Errors
In this tutorial, you'll learn about How to Fix Stack Underflow and Empty Stack Pop Errors. We cover key concepts, practical examples, and best practices.
Stack underflow errors occur when pop or top is called on an empty stack. In array-based implementations, this returns garbage data or underflows the index. In STL std::stack, calling top() or pop() on an empty stack is undefined behavior.
Quick Fix
Wrong
std::stack<int> s;
int val = s.top(); // undefined behavior: empty stack
s.pop();
Undefined behavior: accessing the top of an empty stack.
Right
std::stack<int> s;
if (!s.empty()) {
int val = s.top();
s.pop();
std::cout << val;
}
Empty stack check prevents underflow.
Fix for array-based stack
struct Stack {
int data[100];
int top_ = -1;
bool empty() const { return top_ == -1; }
void push(int val) {
if (top_ >= 99) throw std::overflow_error("Stack full");
data[++top_] = val;
}
int pop() {
if (empty()) throw std::underflow_error("Stack empty");
return data_[top_--];
}
};
Stack s;
try {
s.pop(); // throws std::underflow_error
} catch (const std::underflow_error& e) {
std::cerr << e.what();
}
Stack empty
Fix for expression evaluation
int evaluate(const std::string& expr) {
std::stack<int> s;
for (char c : expr) {
if (isdigit(c)) {
s.push(c - '0");
} else if (c == "+') {
if (s.size() < 2) throw std::runtime_error("Invalid expression");
int b = s.pop(); int a = s.pop();
s.push(a + b);
}
}
if (s.size() != 1) throw std::runtime_error("Invalid expression");
return s.top();
}
Prevention
- Always check
!empty()beforetop()orpop(). - Throw exceptions in custom stack implementations on underflow.
- Use
std::optionalas return type for pop operations. - Check stack size before multiple pops in expression evaluation.
- In algorithms, maintain invariants that guarantee non-empty stacks.
DodaTech Tools
Doda Browser's data structure visualizer shows stack operations and highlights invalid states. DodaZIP archives algorithm runtime traces. Durga Antivirus Pro detects stack manipulation exploits.
Common Mistakes with stack underflow
- Using
returnto exit a function early instead of wrapping a pure value in the monad - Mixing let bindings with <- bindings in do notation, producing type errors
- Overlapping type class instances that cause GHC to reject the program with ambiguous dispatch errors
These mistakes appear frequently in real-world DS code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.
Practice Exercise
Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.
This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.
FAQ
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro