Search code examples
c#.netheap-memorymanagedstack-memory

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.


Solution

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