Skip to content
Tutorials Center
My learning

Topics

C Reference ยท POSIX and Systems

C mmap() function

Reference for mmap() and munmap(): map a file or anonymous memory into your address space, choose protections and sharing flags, sync changes, and avoid mistakes.

mmap() asks the operating system to place a region of memory into your address space. The region can be backed by a file, so that reading and writing the memory reads and writes the file, or it can be anonymous: a fresh block of zeroed pages that belongs to nobody else. munmap() gives the region back.

Memory mapping is what malloc uses for large blocks, what the dynamic loader uses to bring in code, and what many databases use to treat a file as an array of bytes. With a file mapping you skip the read and write calls and the copying that goes with them: the kernel loads pages on demand and writes them back later.

C
#include <sys/mman.h>

void *p = mmap(NULL, length, PROT_READ | PROT_WRITE,
               MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
if (p == MAP_FAILED) { /* error: see errno */ }
munmap(p, length);

Try it

C Anonymous memory and a file mapping

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

C A shared mapping survives fork

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Syntax

C
void *mmap(void *addr, size_t length, int prot, int flags, int fd, off_t offset);
int   munmap(void *addr, size_t length);
int   msync(void *addr, size_t length, int flags);
int   mprotect(void *addr, size_t length, int prot);
Name Description
addr A hint for where to place the mapping. Pass NULL and let the kernel choose.
length Size in bytes. Must be greater than zero. The kernel rounds the region up to whole pages.
prot PROT_READ, PROT_WRITE, PROT_EXEC, combined with bitwise OR, or PROT_NONE for no access. Must not conflict with how the file was opened.
flags Exactly one of MAP_SHARED or MAP_PRIVATE, optionally with MAP_ANONYMOUS (a Linux and BSD extension, in POSIX as an option on some systems).
fd The open file to map, or -1 with MAP_ANONYMOUS.
offset Where in the file the mapping starts. Must be a multiple of the page size.

Returns: the address of the mapping, or MAP_FAILED (which is (void *)-1, not NULL) with errno set. munmap, msync and mprotect return 0 on success and -1 on error.

Errors / undefined behavior: EACCES (file not opened for the requested access), ENOMEM (no address space or memory), EINVAL (bad length, offset or flags). Touching a mapped file page beyond the end of the file raises SIGBUS. Using memory after munmap, or writing to a PROT_READ mapping, raises SIGSEGV.

Usage notes

  • Check for MAP_FAILED. A comparison with NULL is a bug: NULL is never returned on failure.
  • MAP_SHARED vs. MAP_PRIVATE. With MAP_SHARED your writes reach the file and other processes that map it. With MAP_PRIVATE you get a copy-on-write view: writes stay in your process and never reach the file.
  • Anonymous memory is zeroed. That is why mmap is a handy way to get a page-aligned, zero-filled block, and why shared anonymous mappings are a simple way for a parent and its forked children to share data. Without synchronization (a mutex with the PTHREAD_PROCESS_SHARED attribute, or a semaphore) concurrent updates still race.
  • Closing the descriptor does not unmap. The mapping holds its own reference to the file, so close(fd) right after mmap is normal.
  • Data reaches the disk later. Use msync(..., MS_SYNC) when you need the file to be updated at a specific point; munmap and process exit do not guarantee durability against a power loss.
  • You cannot grow a file by writing past its end through a mapping. Extend the file first with ftruncate, then map it.
  • Alignment and size. The page size is usually 4096 bytes; ask sysconf(_SC_PAGESIZE) instead of hard-coding it. Offsets must be multiples of it.
  • Cost. Mapping avoids a copy and lets the kernel share cached pages, but each first touch of a page can cause a page fault. For small files or one sequential pass, plain read is often as fast and simpler.
  • Windows has no mmap; its equivalents are CreateFileMapping and MapViewOfFile.