I know the maximum stack size usually is fixed on link (maybe on windows is that).
But I don't know when the program stack size ( not maximum stack size just used size) used is be fixed to OS. compile ? linked ? execute ?
like this:
int main(){ int a[10]; return 0;}
the program just use 10 * sizeof(int) stack. so, is the stack size fixed?
above all. if the heap size is changed when malloc or free?
Stack size is not explicitly provided to OS, when program is loaded. Instead, OS uses mechanism of page faults (if it is supported by MMU).
If you try to access memory which was not granted by operating system yet, MMU generates a page fault which is handled by OS. OS checks address of page fault and either expands stack by creating new memory page or if you have exhausted stack limits, handles it as stack overflow.
Consider following program running on x86 and Linux:
It faults because of infinite recursion and stack overflow. It actually requires infinite stack to be completed. When program is loaded, OS allocates initial stack and writes it to
%rsp
(stack pointer). Let's look atfoo()
disassembly:After at most 4096 / 16 = 256 calls of
foo()
, you will break page boundary by writing a memory at addressX + 4096
where X is initial%rsp
value. Then page fault will be generated, and OS provide new memory page for stack, allowing program to utilize it.After about 500k of
foo()
calls (default Linux ulimit for stack), OS will detect that application utilizes too many stack pages and send SIGSEGV to it.In an answer to a question I provided the following information:
The BSS/DATA segment contains all the global variables, initialized to a specific value or to zero by default. This segment is part of the executable image. At load time, the heap segment is added to this; however, it is not a "segment" but just the amount of extra data to be allocated as an extension of the loaded BSS/DATA segment. In the same way the stack "segment" is not a true segment but is added to the BSS+heap segment. The stack grows down whereas the heap grows up. If these overlap (more heap used and stack still growing) an "out of memory" error occurrs (heap) or "stack overflow" (stack) - this may be detected with the use of segment registers (Intel) to trigger a hardware generated exception or by using software checks.
This is the traditional way of laying out the segments. Think of older Intel chips where all progeram data must be in 64KB. With more modern chips the same layout is often used where address space of 32MB is used in this layout but only actual physical memory required is used. The stack can thus be pretty big.