Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 817
Zohaib Aslam Avatar asked Feb 23 '26 19:02

Zohaib Aslam


1 Answers

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.

like image 125
James C. Taylor IV Avatar answered Feb 25 '26 09:02

James C. Taylor IV



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!