Tuesday, June 09, 2009

Heap vs. Stack – where does your data reside?

I keep mixing it up between heap and stack, so this post is more of a reminder for me.

Value types go in one container and Reference types go in the other.

Typically value types go into the Stack and reference types go onto the Heap.

Why do I say typically? Because value types that are declared as part of a reference type (members) are stored on the heap.

A more specific rule:

Reference types are always allocated on the Heap.

Value types and pointers are allocated on the Stack if they were defined within a method. But if they (value types and pointers) were declared as member variables of a class (a reference type), then they get allocated on the Heap.

Here is a good article that touches on these issues and more: Heaping vs. Stacking

2 comments:

jdauie said...

Additional commentary from Eric Lippert's Blog:
part 1
part 2

Raj M. Rao said...

The relevant feature of value types is that they have the semantics of being copied by value. Similarly, the relevant feature of reference types is that they have the semantics of being copied by reference.