What happens to the stack when exiting a method?

后端 未结 6 434
长发绾君心
长发绾君心 2021-01-01 20:53

I was reading What and where are the stack and heap?. One thing I am a bit fuzzy on is what happens to the stack after a method exits. Take this image for example:

6条回答
  •  星月不相逢
    2021-01-01 21:58

    During execution of a function, all local variables are created in the stack. That means that the stack grows to make enough room for those variables.

    When the function ends, all the local variables goes out of scope and the stack is rewinded. Nothing else needs to happen, no implicit zeroing memory. But :

    • semantically the variables go out of scope and can no longer be used
    • in the hard way, the stack pointer is rewinded, effectively freeing the memory : it will be useable by next function call

    Above is not only true for functions but can be the same for any block of code since semantically the variables defined in the block go out of scope at end of block.

提交回复
热议问题