unixmemorymemory-managementheap-memory

Stack and heap size allocation question for common Unix OS


In Unix operating systems how are sizes between low and high address of the following picture chosen? I’m assuming this has something to do with Virtual Memory management and allocation of pages.

I’m curious because I recall working with one OS and recursive functions can run out of stack space, whereas the OS provides options to increase stack space for a process. For heap I understand that’s malloc requesting memory which I’m guessing somehow increases heap size dynamically after text, and data are loaded.

a Ref:link


Solution

  • In Unix operating systems how are sizes between low and high address of the following picture chosen?

    The stack size is a process resource limit that you can see by running ulimit -s. When a process is being created by the OS, a stack segment is created whose (fixed) size is determined by the limit. The allocation of the memory pages that the stack will use is handled by the OS virtual memory subsystem.

    The area you have show as "heap" is actually the process data segment. It may or may not be used by a heap. The size of this segment is controlled by the brk() syscall. Assuming that the data segment is managed by a heap allocator (e.g. via malloc and free in C), when the allocator runs out of space, it calls brk() or sbrk() (see https://man7.org/linux/man-pages/man2/brk.2.html) to request more memory. As with the stack segment, the OS virtual memory system takes care of allocating the memory pages as they are needed.

    A process can also use mmap or shmat or similar syscalls to request or map additional memory segments. But that is beyond the scope of this question.

    I’m assuming this has something to do with Virtual Memory management and allocation of pages.

    Yes. Sort of. See above.

    I’m curious because I recall working with one OS and recursive functions can run out of stack space, whereas the OS provides options to increase stack space for a process.

    The stack segment size is fixed; see above. This is actually a good thing1.

    For heap I understand that’s malloc requesting memory which I’m guessing somehow increases heap size dynamically after text, and data are loaded.

    The details of how a heap operates are programming language / process runtime specific. But basically yes. Typically it is done using brk or mmap.


    1 - Unbounded stacks would lead to OS crashes. Any application with an infinite recursion bug would consume all available RAM for its infinite stack. This would lead to severe VM thrashing and worse.