operating-system

What changes occur to address space, pages and segments of a process when we allocate memory at runtime using malloc() /calloc() /realloc() calls?


What changes occur to address space, pages and segments of a process when we allocate memory at runtime using malloc()/calloc()/realloc() system calls, on Linux and Windows? What happens to address space, pages and segments when we free() those allocated memory.

This is OS related theoretical question


Solution

  • malloc() family of functions manage a local heap. They take whole pages from OS and subdivide them into smaller blocks of arbitrary size.

    If malloc already has enough memory received from OS - then no changes happen to address space or pagetables. Malloc will modify its bookkeeping data area to mark a new allocated chunk as "occupied" - but that's it.

    If, however, malloc doesn't have enough memory - it would call OS to ask for more (using brk/mmap syscall on Linux, VirtualAlloc on Windows). If the call succeeds - a new page appears in the address space of a program (previously that area would give you a Segfault/Access Violation - but now it is a valid memory).

    free() returns memory to the malloc pool, so it can be reused by a future malloc() calls. Sometimes, free() can return memory to the OS - but when it happens depends on the particular malloc implementation. Some implementations return memory immediately, while others tend to gobble memory.

    malloc() and free() have no effect on x86 segments. In fact, those are pretty much never changed - they only swap between privileged kernel segments and unprivileged user.