Search code examples
.netheap-memorystack-memory

How to explain heap and stack do not grow towards each other


When I debug these lines of code, I can observe ms/ms2 are instances of value type and they are allocated on stack, and o (boxed MyStruct instance) is reference type and is allocated in managed heap.

I can view the addresses of ms and ms2 from a Watch window in Visual Studio, they are 0x0024f104 and 0x0024f0f0, respectively. So the stack is growing DOWN towards the bottom of the address space. Since stack and heap grow towards each other, the address region for the managed heap should be below 0x0024f0f0. But the address of o is actually 0x01e9312c, which means the heap does not grow towards the stack (although I can observe when new objects are allocated in the heap, their addresses are indeed growing UP).

Can someone help to explain this?

MyStruct ms = new MyStruct(1, 2, 4, 8); //0x0024f104, 16 bytes for ms
Object o = ms;                          //0x0024f100, 4 bytes for variable o
MyStruct ms2 = (MyStruct)o;             //0x0024f0f0, 16 bytes for ms2

Solution

  • Stack and head growing towards each other was a concept valid some 30 years ago.

    Generally you don't have to and should not care of where in memory an object is located.