Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The stack is created by compiler or OS/architecture

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.

like image 598
brett Avatar asked Aug 31 '10 05:08

brett


2 Answers

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.

like image 65
zneak Avatar answered Sep 18 '22 22:09

zneak


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.

like image 30
radman Avatar answered Sep 19 '22 22:09

radman