Why in C++ is stack space allocated for local variable declarations never encountered by the thread of execution? Or, if left undefined by the C++ standard, why do certain compilers allocate stack space for local variable declarations never encountered by the thread of execution? Could a compiler only allocate stack space for variable declarations encountered by the thread of execution and still work?
To illustrate, calling this function in Debug mode where variable chars cannot be encountered results in a stack overflow:
void f()
{
if (false)
{
char chars[INT_MAX];
}
}
The compiler has hoisted the declaration of the local variable. Whether this is done is not defined by the standard, hence the behaviour is implementation specific. Doing so allows the space for all the local variables to be allocated at once, which reduces overhead.
However, with optimisation, the compiler will identify your particular case as dead code and what you are encountering will be eliminated.
1) There's no reason not to. The C++ standard does not promise that variables inside scopes that are not entered during execution will not have space allocated for them.
2) It's faster and simpler. If all the locals get allocated at once, the code to allocate space for locals consists of a one update to the stack pointer at the beginning of the function, and one at the end. If locals within a scope have to be allocated and deallocated at the beginning and end of that scope, you get a lot more stack pointer updates.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With