Question

I have c++ code that works properly in Debian (gcc (Debian 4.7.2-5) 4.7.2), but fails in Ubuntu (gcc (Ubuntu/Linaro 4.7.2-2ubuntu1) 4.7.2). I'm getting stack space reused between variables, similar to what is described in these questions:

In C, do braces act as a stack frame?

C++ stack and scope

except I'm not having nested scopes. Instead code looks similar to this:

TreeWalker walker;
walker.addVisitor(nodeType1, Visitor1());
walker.addVisitor(nodeType2, Visitor2());
...
walker.walkTree(tree);

I could mitigate this issue by allocating on the heap, but I'm wondering what can I do to make sure that local variables are left in place? Would assigning visitors to local variables be enough to ensure they won't be reused? Does standard provides any promise on the stack variables after their last use in function code?

Was it helpful?

Solution

what can I do to make sure that local variables are left in place?

Either use (named) local variables, not temporaries; or modify addVisitor to store a copy of the visitor rather than a reference to it, if that's feasible.

Would assigning visitors to local variables be enough to ensure they won't be reused?

Yes.

Does standard provides any promise on the stack variables after their last use in function code?

Temporaries (unnamed objects created during an expression, such as the visitors you create) live until the end of the full-expression that creates them. So they last until the call to addVisitor returns, but are destroyed before the next line.

Local variables (automatic variables declared within a block of code) last until the program leaves the innermost block in which they are declared. When that happens, each local variable from that block is destroyed in the reverse order of their declarations. So in the following:

{
    Visitor1 visitor1;
    Visitor2 visitor2;
    TreeWalker walker;
    walker.addVisitor(nodeType1, visitor1);
    walker.addVisitor(nodeType2, visitor2);
    //...
    walker.walkTree(tree);
}

it's guaranteed that walker will be destroyed before the visitors, so it will not contain any dangling references even in its destructor.

OTHER TIPS

Visitor1() is not a local variable, it's a temporary. The lifetime of a temporary ends when the full-expression in which it appears ends.

If you need to preserve them, use local variables for them instead of temporaries.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top