Question

During a C++ program execution does stack frame of a particular function always have a constant size or compiler is allowed to do dynamic stack management in some cases, something similar to what alloca() function does? to better describe it I mean offset of a particular local variable or object in the stack frame may change at different executions of function

Was it helpful?

Solution 3

In common implementations, local variables are placed on the stack frame. Some functions may have variables that are accommodated by registers, others will have variables placed on the stack.

Stack frames may also be expanded by non-static variables declared in statement blocks.

There is no standard minimum size for a stack frame. The maximum size of a stack frame depends on the platform and implementation. A common implementation is to have the stack to expand towards the heap and the heap expands towards the stack.

OTHER TIPS

At least in most typical implementations, the stack frame for a variadic function varies depending on how many variables are passed. For example:

printf("%d", 1); // stack frame contains 1 pointer, one int
printf("%d %d", 1, 2); // stack frame contains one pointer, 2 ints.

Whether the implementation is particularly similar to alloca depends on the implementation though (especially since alloca isn't standard, so how or even if it's implemented may vary).

The compiler is allowed to do as it wishes, after all it generates the code and as long as it does what the program in C++ says it is fine. In general, whenever possible, compilers calculate the total needed stack space for the function and reserve that upfront (reducing the number of times the stack register is written to), even if objects are created and destructed on demand.

The standard does not say anything about it (it does not even require you to have a stack), and with C++14 likely something like alloca will be needed since it will likely get a "light" version of C99 VLAs.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top