变量如何存储在堆栈中?

how variables are stored on stack?

我读到有两个内存区域,一个是堆栈,另一个是堆。 int、double、float 等基本数据类型存储在堆栈中,而引用类型存储在堆中。正如我们所知,堆栈是 LIFO ,这意味着最后一个被压入的元素将首先被删除。现在假设以下代码

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

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

Console.WriteLine(second);

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

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

Stack 的行为类似于具有 PUSH 和 POP 的 LIFO insturctions.But 这并不意味着没有 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]].

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

Eric Lippert 有几篇关于该主题的帖子,我建议您阅读。内存管理是一个高级话题。

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

"All VALUE Types will get allocated to Stack" is very, very wrong; struct variables can live on the stack, as method variables. However, fields on a type live with that type. If a field's declaring type is a class, the values are on the heap as part of that object. If a field's declaring type is a struct, the fields are part of that struct where-ever that struct lives.

Even method variables can be on the heap, if they are captured (lambda/anon-method), or part of (for example) an iterator block.