Linux – “automatic stack expansion”

limitlinuxmemoryprocess

getrlimit(2) has the following definition
in the man pages:

RLIMIT_AS
The maximum size of the process's virtual memory (address space) in bytes. This limit affects calls to brk(2), mmap(2) and mremap(2), which fail with the error ENOMEM upon exceeding this limit. Also automatic stack expansion will fail (and generate a SIGSEGV that kills the process if no alternate stack has been made available via sigaltstack(2)). Since the value is a long, on machines with a 32-bit long either this limit is at most 2 GiB, or this resource is unlimited.

What is meant by "automatic stack expansion" here? Does the stack in a Linux/UNIX environment grow as needed? If yes, what's the exact mechanism?

Best Answer

Yes stacks grow dynamically. The stack is in the top of the memory growing downwards towards the heap.

--------------
| Stack      |
--------------
| Free memory|
--------------
| Heap       |
--------------
     .
     .

The heap grows upwards (whenever you do malloc) and the stack grows downwards as and when new functions are called. The heap is present just above the BSS section of the program. Which means the size of your program and the way it allcates memory in heap also affect the maximum stack size for that process. Usually the stack size is unlimited (till heap and stack areas meet and/or overwrite which will give a stack overflow and SIGSEGV :-)

This is only for the user processes, The kernel stack is fixed always (usually 8KB)

Related Question