变量如何存储在堆栈中?

时间:2015-01-11 07:20:13

标签: c# stack heap

我读过有两个内存区域,一个堆栈和另一个堆栈。基本数据类型(如int,double,float等)存储在堆栈中,而引用类型存储在堆上。我们知道堆栈是LIFO,这意味着将推送最后推送的元素。现在假设以下代码

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

因此,first将先被推送,然后是second,然后是third。因此,float类型的变量third将位于堆栈顶部,但如果我使用以下代码(假设在C#中)

Console.WriteLine(second);

当变量second位于堆栈顶部时,如何访问变量third的值?

3 个答案:

答案 0 :(得分:5)

你误解了the stack实际指的是什么。有一个数据结构Stack使用pushpop来存储数据,但基于堆栈和基于头的内存是一个更抽象的概念。您可以尝试查看基于堆栈的Wiki article内存分配,但您还需要了解有关汇编和帧指针的更多信息。有关该主题的全部课程。

答案 1 :(得分:1)

Stack表现为带有PUSH和POP insturctions的LIFO。但这并不意味着没有pop你可以读取堆栈内存。 在你的情况下  你

        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]].

答案 2 :(得分:1)

我认为你误解了这个概念。

Eric Lippert在我推荐阅读的主题上有几个帖子。内存管理是一个高级主题。

另外,found this great answer on what lives on the stack from Marc Gravell,复制如下。

  

"所有VALUE类型都将分配给Stack"非常非常错误;   struct变量可以作为方法变量存在于堆栈中。然而,   类型上的字段。如果字段的声明类型是a   class,值作为该对象的一部分在堆上。如果是一个字段   声明类型是结构,字段是该结构的一部分   结构生活在哪里。

     

即使方法变量被捕获,它们也可以在堆上   (lambda / anon-method),或(例如)迭代器块的一部分。