Reputation: 21
So, I'm curious about this thing I can't figure out.
I'm creating some new objects and passing them to a function which stores them in a std::stack.
However, when i want to delete them - they do not actually get deleted, and as such, memory usage will proceed to climb "forever" with my test loop.
Why?
bool StateMachine::changeState(BaseState *state) {
if (state == nullptr) {
delete states.top();
states.pop();
if (states.size() == 0) {
return false;
}
} else if (state != states.top()) {
states.push(state);
}
return true;
}
Test loop:
while (true) {
machine.changeState(new MenuState);
machine.changeState(nullptr);
}
Using a std::unique_ptr instead of raw works, and now ram usage is constant, but still - I wanna know.
Cheers!
Upvotes: 0
Views: 264
Reputation: 44
Your code should be correct given the preconditions you've mentioned, but notice that you can allocate and delete objects without reclaiming operating system allocated memory, especially if you leave allocation holes in memory. So check both if memory starts growing then stops and for memory leaks elsewhere, like inside BaseState.
If you're in doubt about preconditions, add an else clause in your if and print something. I should never happen, but if it does, then there may be some problem calling states.top().
Upvotes: 1