Domanda

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.

È stato utile?

Soluzione

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.

Altri suggerimenti

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."

(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.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top