Using mmap to allocate private memory

You can use mmap to allocate an area of private memory by setting  MAP_ANONYMOUS in the flags parameter and setting the file descriptor  fd to -1. This is similar to allocating memory from the heap using malloc, except that the memory is page-aligned and in multiples of pages. The memory is allocated in the same area as that used for libraries. In fact, this area is referred to by some as the mmap area for this reason.

Anonymous mappings are better for large allocations because they do not pin down the heap with chunks of memory, which would make fragmentation more likely. Interestingly, you will find that malloc (in glibc at least) stops allocating memory from the heap for requests over 128 KiB and uses ...

Get Mastering Embedded Linux Programming - Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.