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?
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]].
You misunderstand what the stack
is actually referring to. There is a data structure Stack
which uses push
and pop
to store data, but stack based and head based memory are a far more abstract concept. You might try looking at the Wiki article on stack based memory allocation, but you will need to know more about assembly and frame pointers as well. There are entire classes taught on this subject.
I think you have misunderstood the concept.
Eric Lippert's has a several posts on the topic that I would recommend reading. Memory management is an advanced topic.
Also, found this great answer on what lives on the stack from Marc Gravell, copied below.
"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.
链接地址: http://www.djcxy.com/p/82600.html上一篇: 内存管理的值和引用类型
下一篇: 变量如何存储在堆栈上?