It is not mentioned in the cited duplicate or here. Linux uses virtual memory and can allocate more memory that physically available in the system. A naive implementation of calloc()
that simply does a malloc()
plus memset()
in user space will touch every page.
As Linux typically allocates in 4k chunks, all of the calloc()
blocks are the same and initially read as zero. That is the same 4k chunk of memory can be mapped read only and the entire calloc()
space in only taking up approximately size/4k * pointer_size + 4k
. As the program writes to the calloc()
space, a page fault happens and Linux will allocate a new page (4k) and resume the program.
This is called copy-on-write or COW for short. malloc()
will generally behave the same way. For small sizes, the 'C' library will use binning and share 4k pages with other small sized allocation.
So, there are typically two layers involved.
- Linux kernel's process memory management.
- glibc heap management.
If the memory size requested is large and requires new memory allocated to the process, then most of the above applies (via Linux's process memory management). However, if the memory requested is small, then it will be like a malloc()
plus memset()
. In the large allocation size, the memset()
is damaging as it touches the memory and the kernel thinks it needs a new page to allocate.