malloc() does not necessarily unmap free’d pages

Glibc’s malloc uses a combination of brk() and mmap() (where available) system calls depending upon the size of the chunk being allocated and some other factors like holes in the address space. a brk() only increases the data segment of a process in turn increasing the address space of that process. When you free() it, libc only marks this chunk as un-available but it still remains mapped. If malloc() uses mmap(), a free would so a munmap() and then later on accessing a freed memory will result in a seg-fault.
There’s a comment in glibc’s mmap.c that says:

Define HAVE_MMAP as true to optionally make malloc() use mmap() to
allocate very large blocks.  These will be returned to the
operating system immediately after a free(). Also, if mmap
is available, it is used as a backup strategy in cases where
MORECORE fails to provide space from system.
This malloc is best tuned to work with mmap for large requests.
If you do not have mmap, operations involving very large chunks (1MB
or so) may be slower than you'd like.

The default mmap() threshold is 128*1024 bytes (or 128 KB). This value can be changed using mallopt() glibc call:

Enhanced by Zemanta

Leave a Reply

Your email address will not be published. Required fields are marked *