How does memory allocation work

It appears that the stack memory limit is not allocated (anyway, it couldn't with unlimited stack). says:

The C language stack growth does an implicit mremap. If you want absolute guarantees and run close to the edge you MUST mmap your stack for the largest size you think you will need. For typical stack usage this does not matter much but it's a corner case if you really really care

However mmapping the stack would be the goal of a compiler (if it has an option for that).

EDIT: After some tests on an x84_64 Debian machine, I've found that the stack grows without any system call (according to ). So, this means that the kernel grows it automatically (this is what the "implicit" means above), i.e. without explicit / from the process.

It was quite hard to find detailed information confirming this. I recommend Understanding The Linux Virtual Memory Manager by Mel Gorman. I suppose that the answer is in Section 4.6.1 Handling a Page Fault, with the exception "Region not valid but is beside an expandable region like the stack" and the corresponding action "Expand the region and allocate a page". See also D.5.2 Expanding the Stack.

Other references about Linux memory management (but with almost nothing about the stack):

EDIT 2: This implementation has a drawback: in corner cases, a stack-heap collision may not be detected, even in the case where the stack would be larger than the limit! The reason is that a write in a variable in the stack may end up in allocated heap memory, in which case there is no page fault and the kernel cannot know that the stack needed to be extended. See my example in the discussion Silent stack-heap collision under GNU/Linux I started in the gcc-help list. To avoid that, the compiler needs to add some code at function call; this can be done with for GCC (see Ian Lance Taylor's reply and the GCC man page for details).