The first answer here mentioned the following about stack memory in C ++:
When a function is called, the block is reserved at the top of the stack for local variables and some credentials.
This makes sense at the top level, and I wonder how the smart compilers when allocating this memory on their own, given the context of this question : Since the curly braces themselves are not a stack frame in C (I assume this is true for C ++ as well) , I want to check if compilers optimize reserved memory based on variable regions within the same function.
In the following case, I assume that the stack looks like before the function call:
-------- |main()| -------- <- stack pointer: space above it is used for current scope | | | | | | | | --------
And then after calling the f()
function:
-------- |main()| -------- <- old stack pointer (osp) | f() | -------- <- stack pointer, variables will now be placed between here and osp upon reaching their declarations | | | | | | | | --------
For example, given this function
void f() { int x = 0; int y = 5; int z = x + y; }
Presumably, this will just allocate 3*sizeof(int)
+ extra overhead for bookkeeping.
However, what about this function:
void g() { for (int i = 0; i < 100000; i++) { int x = 0; } { MyObject myObject[1000]; } { MyObject myObject[1000]; } }
Ignoring compiler optimizations, which can push out a lot of things from the above, since they actually do nothing, I am interested in the following example in the second example:
- For the
for
loop: will the stack space be large enough to fit all 100,000 ints? - Also, will the stack space contain
1000*sizeof(MyObject)
or 2000*sizeof(MyObject)
?
In general: does the compiler take the variable region into account when determining how much memory is needed for a new stack frame before calling a specific function? If it depends on the compiler, how do some well-known compilers do it?