Where variables of a function is store? on stack or heap?
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.
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.
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.
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."
链接地址: http://www.djcxy.com/p/84360.html上一篇: D3直方图,来自时间戳的日期出现次数
下一篇: 函数的变量存储在哪里? 堆栈或堆?