0

I'm interested in how the stack works and have a problem with understanding how the stack frame destruction occurs. I'm playing with code below:


public class Container
{
    public unsafe int* t1;
    public unsafe int* t2;
    public unsafe int* t3;

    public unsafe void Initialize()
    {
        int t1 = 1;
        int t2 = 2;
        int t3 = 3;


        this.t1 = &t1;
        this.t2 = &t2;
        this.t3 = &t3;

        Console.WriteLine(*this.t1); // 1
        Console.WriteLine(*this.t2); // 2
        Console.WriteLine(*this.t3); // 3
    }
}

static unsafe void Main()
{
    var container = new Container();
    container.Initialize();

    Console.WriteLine(*container.t1); // 1
    Console.WriteLine(*container.t2); // 1
    Console.WriteLine(*container.t3); // 1
}

You can view asm representation this code here

Question: Why do the properties v1,v2,v3 return different values when dereferencing?

Suggestion: When Initialize is finished and returns to the Main function the stack frame that was created for Initialize function is destroyed and memory which was allocated for local variables is cleaned.

But as I know destroying doesn't clean memory, only Stack Pointer and Frame Pointer are restored during the destruction process

Observation: I get the correct value when dereferencing container.t1

Peter Cordes
  • 328,167
  • 45
  • 605
  • 847
Evgeniy Terekhin
  • 596
  • 3
  • 10
  • 2
    The first `WriteLine` will itself use the stack and overwrite the values. If you first copy the values into locals in `Main` you should probably see all three still there. – Jester May 15 '20 at 18:28
  • 1
    Optimized code doesn't waste instructions setting up RBP as a frame pointer; if it needs to reference anything in its stack frame, it does so relative to RSP. – Peter Cordes May 15 '20 at 18:30
  • @Jester, OMG, you are right, I was inattentive. if you want to create a separate comment, I will note it as the answer. Thank you! – Evgeniy Terekhin May 15 '20 at 18:37
  • @PeterCordes, yes, you are right – Evgeniy Terekhin May 15 '20 at 18:38

0 Answers0