C stack / scope, variable lifetime after function completion

void someFunc() { int stackInt = 4; someOtherFunc(&stackInt); } 

Is it possible that the address of stackInt can be redistributed after someFunc completes, which makes 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 the stack variables to the address and expecting that they will still be alive after the function in which they were initialized has ended?

+4
source share
4 answers

Yes, definitely.

You do not need to avoid passing variables associated with the stacks via a link / pointer, although simply by keeping pointers or references to variables associated with the stack.

+3
source

After returning someFunc() and calling another function, 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 stores a copy of the passed pointer, that pointer will remain valid. If he starts a copy of the value that was indicated, this is normal.

So, although transferring stack variables to an address (for example, someOtherFunc() can change the value of stackInt ), and if code appeared in someFunc() in someFunc() , which turned to it after the call, the value cannot be 4 more), it is not safe to store a pointer and expect it to point anywhere when after returning someFunc() .

+1
source
  • It is absolutely normal to pass stack variables as parameters in all possible ways.
  • The listed stack variables will only be overwritten when the function declaring these variables is completed.

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

0
source

Until you create a new thread from someOtherFunc and use stackInt, this will work.

0
source

Source: https://habr.com/ru/post/1307421/


All Articles