I am studying memory management and have a question about how malloc works. The malloc man page states that:
Normally,
malloc()
allocates memory from the heap, and adjusts the size of the heap as required, usingsbrk(2)
. When allocating blocks of memory larger thanMMAP_THRESHOLD
bytes, the glibcmalloc()
implementation allocates the memory as a private anonymous mapping usingmmap(2)
.MMAP_THRESHOLD
is 128 kB by default, but is adjustable usingmallopt(3)
.
To verify it, I did an experiment with a piece of code:
#include<stdlib.h>
#include<stdio.h>
int main()
{
int size = 10;
int *p = malloc(size);
if(p)
{
printf("allocated %d bytes at addr: %p \n", size, p);
free(p);
}
else
{
free(p);
}
return 0;
}
I traced this program with strace to see what syscall was used. Here is the result:
Why in this example did malloc call mmap instead of brk?