Where variables of a function is store? on stack or heap?

若如初见. 提交于 2020-01-03 04:15:29

问题


When a program calls a function, in which type of data structure is memory allocated for the variables in that function? Heap or stack? why?

In my opinion it should store on stack because they are not necessarily reference types. But Where I read the answer, it is stated that they store on heap and free after function returns a value.


回答1:


It is a little more complicated than that and the fact that the stack and heap are used are really implementation details. It makes more sense to talk about lifetime of data. Short lived data will be stored on the stack (or in registers). Long lived data is stored on the heap.

Instances of reference types are always considered long lived, so they go on the heap. Value types can be both. Local value types are typically stored on the stack, but if something extends the lifetime of such a variable beyond the scope of the function, storing it on the stack wouldn't make sense. This happens for captured variables and these will be stored on the heap even if they are value types.




回答2:


Parameters are pushed to the stack before invoking a function. If the parameters are a value type, they can be stored directly. If they are a reference type, they are stored in the heap and a pointer to the memory location is pushed on the stack. When the function returns, the values are popped back off the stack and eventually the garbage collector will notice the memory on the heap no longer has a pointer to it and will clean it up too.




回答3:


You should read this article: http://blogs.msdn.com/b/ericlippert/archive/2010/09/30/the-truth-about-value-types.aspx

And in Eric Lippert's own words:

"in the Microsoft implementation of C# on the desktop CLR, value types are stored on the stack when the value is a local variable or temporary that is not a closed-over local variable of a lambda or anonymous method, and the method body is not an iterator block, and the jitter chooses to not enregister the value."




回答4:


(Edited) If the variables in the function are of reference type, the references would be allocated on the stack but their associated objects will be on the heap. But if they are value type, the allocated memory will be on the stack. (I'm not 100% sure though).

For example, consider the following code.

public int myMethod(int x, int y, int z)
{
    double money;
    myClass myObjectRef = new myClass();
    return x + y + z;
}

In the above method, variables x,y,z and myObjectRef would be created on stack but the object that is made by "new myClass()" statement will be on the heap.



来源:https://stackoverflow.com/questions/22431902/where-variables-of-a-function-is-store-on-stack-or-heap

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!