I have questions regarding stacks and dynamic memory allocation.
1) Does kernel determine the size of the stack dynamically during run time or sets the size before the load time ? If stack size is allocated dynamically how can stack overflow take place (Because if size of stack reaches beyond the limit the page handler will allocate space to grow the stack). Also If dynamically allocated how can stack grow from higher address to lower address(because always the virtual address increments for dynamically allocated storage right?)
2) Also if memory is allocated dynamically using malloc the size of the data region grows right ?
Thanks & Regards,
Mousey.
1) It kind of depends on the OS, but a typical scheme is for the OS to give you one page of virtual memory (pages are commonly 4 KB) for the stack and then marks the virtual memory page immediately after it as a “guard page.” This is a special flag that causes a low-level exception to trigger when an application tries to write into it.
The OS handles the exception when you try to write into the guard page (which happens as you grow the stack past the initial allocation size), allocates that page for you (i.e. maps it to a physical memory page), and reruns your program from the instruction where the faulting write occurred. It will work this time since the page has been backed by real memory.
Past a certain point (commonly 1 MB), the OS will stop doing this and trigger a stack overflow exception. This is just because these are usually indicative of program error, and code that really needs huge stacks can allocate memory for whatever their stack data is on the heap.
2) The data segment doesn’t really “grow.” Modern programs have a fixed virtual memory address space. malloc() uses some scheme to carve up this space and back portions of it with real physical memory.
I think both of your questions hint at wanting a better understanding of how the OS provides physical memory to your programs. The key concept in modern systems is virtual memory. Wikipedia’s page on virtual memory is a good place to start.
If you want to develop detailed knowledge, an OS textbook would be a good place to start. Preferably one that’s better than whatever I had when I took that OS course in college 🙂