Skip to content

How to Fix Stack Underflow and Empty Stack Pop Errors

DodaTech Updated 2026-06-24 2 min read

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.

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() before top() or pop().
  • Throw exceptions in custom stack implementations on underflow.
  • Use std::optional as 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

  1. Using return to exit a function early instead of wrapping a pure value in the monad
  2. Mixing let bindings with <- bindings in do notation, producing type errors
  3. 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

What happens when you call pop() on an empty std::stack?

std::stack::pop() on an empty stack is undefined behavior. The program may crash, return garbage, or silently corrupt data. Always check empty() first.

What is the difference between stack underflow and stack overflow?

Stack underflow occurs when popping from an empty stack. Stack overflow occurs when pushing to a full stack (fixed-size implementations). Both are logic errors that need defensive checks.

How do I safely pop from a stack in a multithreaded environment?

Use a mutex to protect the stack, or use a lock-free stack implementation. Always check emptiness inside the critical section to prevent race conditions.

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro