This question is a follow up of my previous question
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.