Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what is stack space reusage

Tags:

There is an option "-fstack-reuse" at the gcc at code generation conventions.

https://gcc.gnu.org/onlinedocs/gcc-7.1.0/gcc/Code-Gen-Options.html#Code-Gen-Options

When functions return; their stack also are rewinding. But what does stack reuse option mean exactly ?

like image 627
RedArrow Avatar asked Feb 22 '18 20:02

RedArrow


2 Answers

Previous GCC versions were rather conservative when it came to reusing stack allocations even though the lifetimes of the objects were not overlapping. This had the effect that a lot of broken code which referenced to out-of-scope local variables or already-destructed temporary objects worked by accident. The -fstack-reuse option is there to provide some level of support for compiling such broken code (although it can probably still break due to other optimizations kicking in).

The option does not affect what happens when a function returns. With or without this option, the stack frame is always destroyed, and all local objects cease to exist. It only affects scope exit (where named variables are deallocated) and the completion of the evaluation of full expressions in C++ (where temporary objects are deallocated).

If your code avoids dangling pointers, the option is of no use to you.

like image 177
Florian Weimer Avatar answered Sep 20 '22 13:09

Florian Weimer


The GCC documentation has a very clear example for stack reuse:

int *p;
{
    int local1;

    p = &local1;
    local1 = 10;
    ...
} // local1 lifetime is over, but p still points to local1
{
    int local2;
    local2 = 20;
    ...
} // local2 might reuse local1 space

if (*p == 10)  // out of scope use of local1
{
    ...
}

So, the option basically means if each local variable has a dedicated stack space. If option is used (default), local variables with non-overlapping lifetimes might use the same stack space (as variables local1 and local2 in the example above.

It is just for the local variables and temporaries, it has nothing to do with stack clean-up.

The stack clean-up is happening always after return and regardless of the -fstack-reuse option. But due to the option, we might need to allocate (and clean-up after return) more space on stack for the same number of local variables.

like image 32
Andriy Berestovskyy Avatar answered Sep 23 '22 13:09

Andriy Berestovskyy