I have a question about the following C code:
void my_function()
{
int i1;
int j1;
// Do something...
if (check_something())
{
int i2;
int j2;
// Do something else...
}
// Do some more stuff...
}
Are there any guarantees about when stack space is allocated/deallocated for i2 and j2 or does it depend on the compiler? I would expect the stack pointer to be adjusted down when i2 and j2 come into scope and adjusted back up when they go out of scope, but then thought some compilers may just "optimize" the whole thing and account for variables in a nested scope when the function is first entered.
I know I can look at the assembly code generated by my compiler, but was wondering if the implementation can be left up to the compiler.
Thanks!
When a new local variables is declared, more stack memory is allocated for that function to store the variable. Such allocations make the stack grow downwards. After the function returns, the stack memory of this function is deallocated, which means all local variables become invalid.
If local variables are required, they are allocated on the stack. By adjusting the rsp register, additional memory is allocated on the stack for locals. As such, when the function is completed, the memory used for the stack-based local variables is released (and no longer uses memory).
The allocation of Local Variables occurs when the calling VI is loaded into memory. If it is a stand-alone VI, then the memory for the Local Variable is allocated at run-time and deallocated at the end of its run.
Whenever an object is created, it's always stored in the Heap space and stack memory contains the reference to it. Stack memory only contains local primitive variables and reference variables to objects in heap space.
There are no guarantees.
Different optimization flags will likely result in different methods of saving variables.
The compiler can even make 1 or more variables not use the stack at all and keep them in registers for the whole duration of the function execution.
The compiler is free to do whatever it wants, as long as the semantics of the language are reserved. In other words, i2
and j2
can be bound to memory places before the execution reaches the entry point of their block, and can be unbounded any time as long as that doesn't affect the semantics of your code.
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