我读过有两个堆栈的内存区域,一个是堆栈,另一个是堆。基本数据类型(如int,double,float等)存储在堆栈中,而引用类型存储在堆中。众所周知,堆栈是LIFO
指最后压入的元素将被首先移除。现在假设以下代码
int first = 10;
double second = 20.0;
float third = 3.0F;
因此,first
将先被推,然后second
再被推third
。因此third
,类型为float的变量将位于堆栈的顶部,但是如果我使用以下代码(假设在C#中)
Console.WriteLine(second);
second
当变量third
位于堆栈顶部时,如何访问变量的值?
堆栈的行为与LIFO相同,具有PUSH和POP指令。但这并不意味着没有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]].
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句