Search code examples
c#heap-memorystack-memory

how variables are stored on stack?


I've read that there are two regions of memory one stack and other heap. Basic data types like int, double, float etc. are stored on stack while reference types are stored on heap. As we know that stack is LIFO that means last element pushed will be removed first. now assuming following code

int first = 10;
double second = 20.0;
float third = 3.0F;

so, first will be pushed first, then second and then third. so variable third which is of type float will be on top of the stack but if I use following code (assuming in C#)

Console.WriteLine(second);

how value of variable second will be accessed while variable third is on top of the stack?


Solution

  • Stack behaves as LIFO with PUSH and POP insturctions.But that doesnt mean without pop you can read the stack memory . In your case you

            push int first            (* its not a opcode of machine, just trying to explain)
            push  double second
            push float third 
    
            Now you have 2 options to access the variables that you have pushed.
    
           1) pop -> This is the one that reads and makes stack look like lifo.
             if you pop it
                 stack will be
                        int first
                        double second.
                Bsically it removes(not exactly,just a register is chaged to show the stacks last valid memory position)
    
          2) But if you want you can jst read it without pop.Thus not removing the last times.
             So you will say Read me  double.And it will access the same way it does in heaps..
                      That will cause machine to execute  a mov instruction .
    
                 Please note its EBP(Base pointer) and ESP(Stack pointer) that points to the location of a stacks variables.And machines read variables   as  mov eax,[ebp+2(distance of "second" from where base pointer is now pointing]].