Let's say we want to allocate a block from the heap by using malloc. When allocating a a large size of memory, malloc calls mmap internally and for a small size allocation, malloc calls brk internally.

Note that the heap is continuous when use sbrk() or brk()

Let say my allocation is relative medium size and malloc calls brk internally.

let's say I call malloc(small); malloc(medium); free(medium)

according to this article The history of Unix's confusing set of low-level ways to allocate memory

If you free()d the right things to create a block of unused space at the top of the break, malloc() and company might eventually call brk() or sbrk() to shrink the program's break and give the memory back to the OS.

since the free medium block is the last one(the small allocated block is the second last one), so the memory will be given back to OS.

Below is my questions:

  1. My understanding about the statement "the memory will be given back to OS" is: the free block's mappings between virtual memory and physical memory are dropped, other processes can use the physical memory that was originally occupied by this free block. Is my understanding correct?

  2. this time I call malloc(medium); malloc(small); free(medium) Since there is still an allocated block in the end, does the free block's mapping between virtual memory and physical memory still exist? can other processes use this free block's physical memory?

1 Answer 1

  1. There are other mechanisms by which physical memory can be re-used for other purposes, swap in particular in this case — if memory pressure is high enough, a process’s physical memory can be swapped out to make room for something else.

    Nowadays, the main benefit of giving memory back to the operating system is that the operating system then knows that the memory won’t be used again, and therefore it can discard corresponding physical memory without any further ceremony. (See my answer to the related SO question for details.)

  2. Mappings between virtual memory and physical memory are somewhat fluid; see the above point about swap. In your scenario, the virtual address space allocated to the process can’t change, because the program break can’t be reduced, and the kernel has to assume that any physical memory mapped to it is “precious” and contains important data. But that doesn’t mean that the kernel can’t re-purpose the physical memory; it only means that it has to ensure, in doing so, that the data stored there isn’t lost.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .