Ranking Stackingblocks
Ranking Stackingblocks

Reputation: 607

C stack/scope, variable's lifetime after functions ends

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?

Upvotes: 4

Views: 633

Answers (4)

Jack
Jack

Reputation: 1438

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

Upvotes: 0

Vineel Kumar Reddy
Vineel Kumar Reddy

Reputation: 4726

  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.

Upvotes: 1

Jonathan Leffler
Jonathan Leffler

Reputation: 754450

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.

Upvotes: 1

Dean Harding
Dean Harding

Reputation: 72668

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.

Upvotes: 3

Related Questions