Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why in C++ is stack space allocated for local variable declarations never encountered by the thread of execution?

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];
    }
}
like image 681
Neil Justice Avatar asked Apr 12 '12 16:04

Neil Justice


2 Answers

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.

like image 180
Mike Kwan Avatar answered Oct 28 '22 23:10

Mike Kwan


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.

like image 26
mjfgates Avatar answered Oct 29 '22 00:10

mjfgates