Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When is stack space allocated for local variables?

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!

like image 213
Neal Stublen Avatar asked Nov 06 '09 15:11

Neal Stublen


People also ask

Does a local variable allocate space on the stack?

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.

How are local variables allocated on the stack?

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).

How memory is allocated for local variables?

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.

Where are local variables stored stack or heap?

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.


2 Answers

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.

like image 55
pmg Avatar answered Oct 24 '22 09:10

pmg


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.

like image 40
Khaled Alshaya Avatar answered Oct 24 '22 09:10

Khaled Alshaya