Skip to main content
gamedev.net
🔒 Locked

Strange Stack Problem

Started by TheJakub May 30, 2003 at 2:46 PM 5 replies 1.3k views
Original Post
TheJakub
TheJakub
I'm coding in C++ in a Visual Studio .Net environment. I have a simple stack declared in my program: std::stack<object*> objStack; Nothing wrong there.. Now, this is the code where I encounter a problem. //the stacks size == 0 if(something == "yes") { Object* newObj = new Object(); objStack.push(newObj); } //the stacks size == 1 if(something == "no") { objStack.pop(); } //the stacks size == 0 Looking at this code, its very basic and everything seems fine. But what I see happening in the Watch List of values is that right after the program steps into the yes block and the object is pushed onto the stack, even though the program never seems to enter the no block, the stack still seems to pop and the size then equals 0. When I comment out the objStack.pop() line, then the stack's size remains 1. I've even tried putting this as a test: if(2 == 4) { objStack.pop(); } which is always false, yet I still get the same exact result. This is driving me insane, it just doesnt make any sense.. [edited by - TheJakub on May 30, 2003 3:49:37 PM] [edited by - TheJakub on May 30, 2003 3:50:00 PM]
Zipster
Zipster
Is there a warning for that? Like "empty branching block" or something? Seems like their should be
Namethatnobodyelsetook
Namethatnobodyelsetook
In recent MS compilers you get "Warning [num]: Empty controlled statement, is this the intent?". Before recently no compiler ever complained as every part of it is valid code, without ambiguity, or loss of precision. Never mind that it''s obviously a fault, the compiler had no reason to complain.
Zipster
Zipster
Clearly a semicolon directly after an if would warrant a warning, no?
darookie
darookie
quote:
Original post by Zipster
Clearly a semicolon directly after an if would warrant a warning, no?

Depends on the warning level you set.
darookie
darookie
Even though the code seems very basic it has an obvious memory leak:


if(something == "no")
{
objStack.pop(); // <- pointer to topmost object gets lost
}


will cause a leak with the topmost object. The "clean" way would look similar to this:


if(something == "no" && !objStack.empty())
{
delete objStack.top(); // free topmost object
objStack.pop(); // remove invalid pointer from stack
}



Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.