mmap() — Linux system interface
Map virtual memory. NULL lets the kernel choose an address; length must be positive. PROT_READ, PROT_WRITE and PROT_NONE govern access. MAP_PRIVATE provides private copy-on-write updates; MAP_SHARED shares updates with other mappings where applicable. MAP_ANONYMOUS uses no file (pass -1 and zero offset). File offsets must be page-aligned. Check MAP_FAILED, not NULL. EINVAL can indicate invalid length or flags; ENOMEM and EACCES have other causes. Avoid MAP_FIXED because it can replace existing mappings. Release a successful mapping with munmap; closing a file descriptor does not unmap it. Compile the complete C example in a fresh private working directory using gcc -std=c17 -Wall -Wextra -Wpedantic -Werror example.c -o example; run ./example. Linux-specific interface or flags; examples target Linux/glibc on x86_64. These are libc-facing signatures, not raw architecture-specific syscall ABIs.
Formal Syntax & Structure
#include <sys/mman.h>void *mmap(void *addr, size_t length, int prot, int flags, int fd, off_t offset);Parameters & Attributes
| Name | Type | Description |
|---|---|---|
| addr | void * | Address hint or NULL. |
| length | size_t | Length in bytes, positive. |
| prot | int | Protection flags. |
| flags | int | Mapping type and options. |
| fd | int | Backing descriptor or -1 for anonymous mapping. |
| offset | off_t | Page-aligned file offset; zero for anonymous mapping. |
Return Value
Mapping address, or MAP_FAILED with errno on failure.
Working Example
#define _GNU_SOURCE#define _POSIX_C_SOURCE 200809L#include <errno.h>#include <stdio.h>#include <stdlib.h>#include <unistd.h>#include <sys/mman.h>
/* A failed check ends this short-lived demonstration. */#define CHECK(x) do { if (!(x)) { \ fprintf(stderr, "check failed at line %d: %s\n", __LINE__, #x); \ return EXIT_FAILURE; \} } while (0)
int main(void){ long page = sysconf(_SC_PAGESIZE); CHECK(page > 0); unsigned char *m = mmap(NULL, (size_t)page, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0); CHECK(m != MAP_FAILED); CHECK(m[0] == 0); m[0] = 42; CHECK(m[0] == 42); CHECK(munmap(m, (size_t)page) == 0); CHECK(mmap(NULL, 0, PROT_READ, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0) == MAP_FAILED && errno == EINVAL); puts("anonymous zero-filled page; write verified; zero length EINVAL"); return EXIT_SUCCESS;}