munmap() — Linux system interface
Remove mappings in the given virtual address range. The starting address must be page-aligned and length positive; affected pages are unmapped even when length is not a page multiple. An unmapped range is not necessarily an error on Linux. No access through stale pointers is permitted; synchronize with other users before unmapping. EINVAL can indicate invalid alignment or zero length. Unmapping is not a durability guarantee for file data; use appropriate synchronization and storage semantics. 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>int munmap(void *addr, size_t length);Parameters & Attributes
| Name | Type | Description |
|---|---|---|
| addr | void * | Page-aligned mapping start. |
| length | size_t | Positive byte length. |
Return Value
0 on success. On failure, returns -1 and sets errno.
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 > 1); unsigned char *m = mmap(NULL, (size_t)page, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0); CHECK(m != MAP_FAILED); CHECK(munmap(m + 1, (size_t)page - 1) == -1 && errno == EINVAL); m[0] = 7; CHECK(m[0] == 7); CHECK(munmap(m, (size_t)page) == 0); puts("unaligned unmap rejected; aligned unmap succeeded"); return EXIT_SUCCESS;}