I realize that malloc
calls 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
My questions:
If there are gaps between each block, then does
brk
still have a reason to exist? since the definition ofbrk
is to point to the top of the heap as the picture below shows:Let's say the first
malloc
get a block(first block in the above picture) in the heap, the secondmalloc
might get a second block whose starting address is below the first block's, then doesbrk
points 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?