Local variable still exists after function returns

前端 未结 5 2184
暖寄归人
暖寄归人 2021-01-05 20:00

I thought that once a function returns, all the local variables declared within (barring those with static keyword) are garbage collected. But when I am trying

5条回答
  •  盖世英雄少女心
    2021-01-05 20:25

    If you really want it to loose the value, perhaps call another function with at least a few lines of code in it, before doing the printf by accessing the location. Most probably your value would be over written by then.

    But again as mentioned already this is undefined behavior. You can never predict when (or if at all) it crashes or changes. But you cannot rely upon it 'changing or remaining the same' and code an application with any of these assumptions.

    What i am trying to illustrate is, when you make another function call after returning from previous one, another activation record is pushed on to the stack, most likely over writing the previous one including the variable whose value you were accessing via pointer.

    No body is actually garbage collecting or doing a say memset 0 once a function and it's data goes out of scope.

提交回复
热议问题