Home > Linux/Linux kernel > malloc() does not necessarily unmap free’d pages

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
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: