I realize that
mmap internally and pass
NULL as the first argument to
mmap so that the kernel will choose a suitable virtual address for the mapping, which means
malloc will not necessarily create a mapping in the heap area(indicated by brk pointer).
If this is true, that means there will be a lot of gaps between each block in virtual memory after multiple
malloc calls since each
malloc return a new virtual address which is not contiguous to previous one
If there are gaps between each block, then does
brkstill have a reason to exist? since the definition of
brkis to point to the top of the heap as the picture below shows:
Let's say the first
mallocget a block(first block in the above picture) in the heap, the second
mallocmight get a second block whose starting address is below the first block's, then does
brkpoints to the end of the first block or the second block? below is a picture depicting this problem:
So once we free one particular block, the allocator normally needs to coalesce adjacent free blocks with it so that those three blocks can be combined into a large free block. but since now each block is not contiguous in virtual memory, we cannot coalesce free those blocks then isn't this dynamic memory allocation very inefficient?