siskat siskat - 1 month ago 19
C++ Question

list::back() causes stack overflow

My application compiles without any error/warning. At runntime I'm getting a strange stack overflow when calling the list::back() function (@std::_Iterator_base12::_Orphan_me() Line 193).

class Stock
{
public:
bool falling = false;
list<int> peaks;
list<int> bottoms;

void ProcessOption(int value)
{
if (falling)
{
if (bottoms.empty()) {
bottoms.push_back(value);
return;
}

int& lastValue = bottoms.back(); //<- Error
if (value < lastValue) {
bottoms.pop_back();
bottoms.push_back(value);
}
else if (value > lastValue) {
falling = false;
ProcessOption(value);
}
}
else
{
if (peaks.empty()) {
peaks.push_back(value);
return;
}

int& lastValue = peaks.back(); //<- Error
if (value > lastValue) {
peaks.pop_back();
peaks.push_back(value);
}
else if (value < lastValue) {
falling = true;
ProcessOption(value);
}
}
}
};


The debugger confirms that both lists including one (valid) element when calling the function. I've tested it with up-to-date MSVC++ 2013 and 2015 compiler.

NPE NPE
Answer

The exact line where you get the error is not the root cause. The underlying issue is that ProcessOption() keeps calling itself until you run out of stack space.

To confirm this, use your debugger to examine the call stack at the point of the crash.