Is the stack grown only on function input?

In C, you can declare variables inside blocks. Is there space for variables declared inside allocated blocks (i.e., the stack expands) when entering a function, or only later, when entering a block?

I know that I can answer the question by letting go of the debugger and looking at the disassembly, but I am interested to find out if the behavior between different platforms / compilers is compatible and whether it can change as a result of optimization.

EDIT: The answer is "this implementation is defined." It seems that most of the implementation will really only do this when entering a function, except for arrays of dynamic size and alloca() . See the comments on this question and the accepted answer for more details.

+7
c
source share
1 answer

From the point of view of the C programming language, all that is guaranteed is that variables with automatic storage time (local variables) will have their own memory created and destroyed when necessary, when the program is launched. As far as I know, this full implementation is defined if and when memory for each variable will be allocated and freed.

In extreme cases, variables may not even get the memory assigned to them if they are local variables that can be stored inside registers. In this case, many different variables can have the same location in memory, although technically speaking, they all exist at the same time, provided that the compiler could notice that the variables should never coexist. On the other hand, space for variable-length arrays cannot be allocated until the size is known, therefore, if the compiler cannot perform static analysis and determine that memory is required for the array earlier, you may have to defer allocation until until the point where the VLA is declared.

Hope this helps!

+7
source share

All Articles