变量如何存储在堆栈中?

问题描述 投票:0回答:3

我读到有两个内存区域,一个是堆栈,另一个是堆。基本数据类型(如 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
的值?

c# heap-memory stack-memory
3个回答
5
投票

您误解了

the stack
实际上指的是什么。有一种数据结构
Stack
,它使用
push
pop
来存储数据,但基于堆栈和基于头的内存是一个更加抽象的概念。您可以尝试查看有关基于堆栈的内存分配的Wiki 文章,但您还需要了解有关程序集和帧指针的更多信息。整个课程都讲授这个主题。


2
投票

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

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

此外,在 Marc Gravell 的堆栈中找到了这个很好的答案,复制如下。

“所有 VALUE 类型都将分配到堆栈”是非常非常错误的; 结构变量可以像方法变量一样存在于堆栈中。然而, 类型上的字段与该类型一起存在。如果字段的声明类型是 类,值作为该对象的一部分位于堆上。如果一个字段的 声明类型是一个结构体,字段是该结构体的一部分 无论该结构存在于何处。

即使是方法变量也可以位于堆上,如果它们被捕获的话 (lambda/匿名方法),或(例如)迭代器块的一部分。


1
投票
堆栈的行为类似于具有 PUSH 和 POP 指令的 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]].
    
© www.soinside.com 2019 - 2024. All rights reserved.