Skip to content
Advertisement

not all malloc’ed memory is “heap” and each block is not contiguous in virtual memory?

It seems that malloc calls mmap internally as :

//not 100% correct onlyfor demo purpose
// void *mmap(void *start, size_t length, int prot, int flags, int fd, off_t offset);

void *malloc(size_t size){
  ...
  mmap(NULL, size,...);   
  ...           
}

so malloc passes NULL as the first argument for mmap as starting address, so 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). enter image description here

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, and those virtual addresses has nothing to do with brk, So once we free one particular block, then we cannot coalesce adjacent free blocks with the one we freed since each block is not contiguous in virtual memory, then isn’t this dynamic memory allocation very inefficient?

Advertisement

Answer

The reason for using mmap in malloc for large blocks is exactly that when the block is freed it can be reclaimed by the OS when it is munmapped.

This is unlike the standard brk/sbrk “heap” where it is hardly ever possible to move the program break down, just because the heap is used for exactly for the reason that the allocations/deallocations need not happen in exact LIFO order – then your only hope is try to coalesce adjacent free memory blocks…

Advertisement