views:

85

answers:

4

I've searched a while but no conclusive answer is present on why value types have to be allotted on the stack while the reference types i.e. dynamic memory or the objects have to reside on the heap. why cannot the same be alloted on the stack?

A: 

Local variables are allocated in the stack. If that was not the case, you wouldn't be able to have variables pointing to the heap when allocating variable's memory. You CAN allocate things in the stack if you want, just create a buffer big enough locally and manage it yourself.

Otávio Décio
So basically your are making a custom managed heap on your stack. ;)
bjarkef
@bjarkef - hey, one does what one has to get done :)
Otávio Décio
+1  A: 

They can be. In practice they're not because stack is a typically scarcer resource than heap and allocating reference types on the stack may exhaust it quickly. Further, if a function returns data allocated on its stack, it will require copying semantics on the caller's part or risk returning something that will be overwritten by the next function call.

Value types, typically local variables, can be brought in and out of scope quickly and easily with native machine instructions. Copy semantics for value types on return is trivial as most fit into machine registers. This happens often and should be as cheap as possible.

plinth
+1  A: 

It is not correct that value types always live on the stack. Read Jon Skeet's article on the topic:

Memory in .NET - what goes where

0xA3
A: 

I understand that the stack paradigm (nested allocations/deallocations) cannot handle certain algorithms which need non-nested object lifetimes.

just as the static allocation paradigm cannot handle recursive procedure calls. (e.g. naive calculation of fibonacci(n) as f(n-1) + f(n-2))

I'm not aware of a simple algorithm that would illustrate this fact though. any suggestions would be appreciated :-)

Gyom