What is stack space reuse?

There is the option "-fstack-reuse" in gcc to symbolize code generation.

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

When functions return; their stack is also rewound. But what does the stack reuse option mean?

+5
source share
2 answers

Previous versions of GCC were fairly conservative when it came to reusing stack distributions, although the lifetime of objects did not overlap. This led to the fact that a large number of broken code that referenced local variables that did not have visibility or already destroyed temporary objects worked by chance. The -fstack-reuse option is intended to provide some level of support for compiling such broken code (although it may still be interrupted due to other optimization attempts).

This parameter does not affect what happens when the function returns. With this option or without it, the stack frame is always destroyed, and all local objects cease to exist. This only affects the output of the area (where named variables are freed) and the completion of the evaluation of complete expressions in C ++ (where temporary objects are freed).

If your code avoids dangling pointers, this option is not suitable for you.

+3
source

The GCC documentation has a very clear example of 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 { ... } 

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

This is only for local variables and time series, it has nothing to do with clearing the stack.

Clearing the stack always occurs after returning and regardless of the -fstack-reuse parameter. But due to the option, we may need to allocate (and clear after returning) more stack space for the same number of local variables.

+1
source

Source: https://habr.com/ru/post/1275522/


All Articles