1

I'm working on some code for an extra credit project and came across something peculiar that I wanted to see if someone could explain for a better understanding. I have a for loop that populates a std::stack and then another that pops the stack for the same amount of time it's populated. I was wondering what would happen if I attempted to pop() when the stack itself is empty already.

Andy Ni
  • 21
  • 5

2 Answers2

4

If you are using the default std::stack container of std::deque, calling pop() on an empty stack would invoke undefined behavior.

"undefined behavior" means that your program's behavior can no longer be relied upon in any way.

Drew Dormann
  • 59,987
  • 13
  • 123
  • 180
3

Here's a documentation trail to follow. You are asking about the behavior of std::stack::pop() in a certain situation. So start with the documentation for that function.

std::stack<T,Container>::pop

Effectively calls c.pop_back()

It is not explicitly clear what is meant by c, but further down the page is a mention of Container::pop_back, so it is reasonable to infer that that is the next thing to look up. (Note that Container is the second template parameter.) You might have a difficulty here if you did not specify a second template parameter for your stack. In that case, back up to the documentation for std::stack to see what the default is.

std::stack

By default, if no container class is specified for a particular stack class instantiation, the standard container std::deque is used.

Aha! So we need to look up the pop_back() member of std::deque.

std::deque<T,Allocator>::pop_back

Calling pop_back on an empty container results in undefined behavior.

There's your answer: undefined behavior. Now you might be asking yourself what is undefined behavior in C++? In brief, undefined behavior allows your program's behavior to be whatever is convenient for the compiler. Technically, it allows any behavior whatsoever, but in practice, compilers just do whatever is convenient.

JaMiT
  • 14,422
  • 4
  • 15
  • 31