tags:

views:

163

answers:

4
void someFunc()
{
    int stackInt = 4;

    someOtherFunc(&stackInt);
}

Is it the case that stackInt's address space could be reallocated after someFunc ends, making it unsafe to assume that the value passed to someOtherFunc represents the stackInt variable with value 4 that was passed to it? In other words, should I avoid passing stack variables around by address and expecting them to still be alive after the function they were initialised in has ended?

+3  A: 

Yes, definitely.

You don't have to avoid passing stack-allocated variables by reference/pointer altogether, though, just storing pointers or references to stack-allocated variables.

Dean Harding
+1  A: 

After someFunc() returns and another function is called, the space that was used for stackInt will be used for some other variable in the new function. Therefore, the function someOtherFunc() cannot safely assume that if it keeps a copy of the pointer it is passed, that pointer will remain valid. If it stashes a copy of the value that was pointed at, that is fine.

So, although it is fine to pass stack variables around by address (so, for example someOtherFunc() could modify the value of stackInt and, if there was code in someFunc() that accessed it after the call, the value might not be 4 still), it is not safe to store the pointer and expect it to point to anywhere valid after someFunc() returns.

Jonathan Leffler
A: 
  1. It is absolutely fine to pass stack variables as parameters in all possible ways
  2. The stack allocated variables will be overwritten only when the function declaring those variables is completed its execution.

So until you return from someFunc() there is no harm to stackInt.

Vineel Kumar Reddy
A: 

As long as you don't spawn new thread from someOtherFunc and use stackInt there, this will work.

Jack