Are these objects’s references on the Stack or on the Heap?

You are asking questions about implementation details, so the answer will depend upon the particular implementation. Let’s consider a version of your program that actually compiles:

class A { public int VarA; }
class X
{
    static void Main(string[] args)
    {
        A a1 = new A();
        a1.VarA = 5;
        A a2 = a1;
        a2.VarA = 10;
    }
}

here’s what happens on Microsoft’s CLR 4.0, running C# 4.0, in Debug mode.

At this point the stack frame pointer has been copied into register ebp:

Here we allocate heap memory for the new object.

A a1 = new A();
mov         ecx,382518h 
call        FFE6FD30 

That returns a reference to a heap object in eax. We store the reference in stack slot ebp-48, which is a temporary slot not associated with any name. Remember, a1 has not been initialized yet.

mov         dword ptr [ebp-48h],eax 

Now we take that reference we just stored on the stack and copy it into ecx, which will be used for the “this” pointer to the call to the ctor.

mov         ecx,dword ptr [ebp-48h] 

Now we call the ctor.

call        FFE8A518 

Now we copy the reference stored in the temporary stack slot into register eax again.

mov         eax,dword ptr [ebp-48h] 

And now we copy the reference in eax into stack slot ebp-40, which is a1.

mov         dword ptr [ebp-40h],eax 

Now we must fetch a1 into eax:

a1.VarA = 5;
mov         eax,dword ptr [ebp-40h] 

Remember, eax is now the address of the heap-allocated data for the thing referenced by a1. The VarA field of that thing is four bytes into the object, so we store 5 into that:

mov         dword ptr [eax+4],5 

Now we make a copy of the reference in the stack slot for a1 into eax, and then copy that into the stack slot for a2, which is ebp-44.

A a2 = a1;
mov         eax,dword ptr [ebp-40h] 
mov         dword ptr [ebp-44h],eax 

And now as you’d expect again we get a2 into eax and then deference the reference four bytes in to write 0x0A into the VarA:

a2.VarA = 10;
mov         eax,dword ptr [ebp-44h] 
mov         dword ptr [eax+4],0Ah

So the answer to your question is that references to the object are stored in the stack in three places: ebp-44, ebp-48 and ebp-40. They are stored in registers in eax and ecx. The memory of the object, including its field, is stored on the managed heap. This is all on x86 in the debug build, of Microsoft’s CLR v4.0. If you want to know how stuff is stored on the stack, heap and registers in some other configuration, it could be completely different. References could all be stored on the heap, or all in registers; there might be no stack at all. It totally depends on how the authors of the jit compiler decided to implement the IL semantics.

Leave a Comment