This question is a follow up of my previous question
stack growth direction
I would like to know whether stack is created by a compiler or OS/architecture ? Also how does OS knows about these compiler specific things ? For ex: C++ allows variables to create data on stack and heap while java allows only heap.
Also if stack is created on heap as mentioned in the post how can system know about it because the system knows only about stack pointer and base pointer.
The stack is a memory location allocated for your program by the OS. Once it's allocated, the OS sets a register (on x86, it's esp
) to where the stack is and then it starts your program. Compilers know that if they use the value in this register as the stack pointer, they'll be okay. Then they do whatever they want to do with it. The OS just allocates a zone. It doesn't care about how it's used after.
The OS doesn't know if your program will use mostly the stack or the heap. However, since most programming languages use the stack in a way or another, it knows it should allocate one. For instance, Java stores its objects on the heap, but most implementations of the JVM will use the stack to maintain call frames (and primitive local variables), so it needs the stack too.
The stack is most definitely defined by the compiler, the OS allocates the space for it but that is relatively trivial. The stack is a dedicated place in memory that is used by the compiler (in so much as the compiler defines the instructions that use it) to control program execution flow and store local variables etc.
So the OS doesn't know about the compiler specific stuff. The stack is still stored in main memory it is just not part of memory that you (the programmer) can directly control.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With