Memory-Mapped Files with mmap in C
mmap (<sys/mman.h>) maps files (or anonymous memory) directly into the address space: void *p = mmap(NULL, len, PROT_READ, MAP_PRIVATE, fd, 0); turns file bytes into an array you index — no read calls, no buffers, with the OS paging data on demand. Writes to MAP_SHARED mappings persist back to the file, making mmap the fastest IPC and file-update mechanism available.
Unmap with munmap when done (leaked mappings persist to exit), handle SIGBUS on truncated files, and prefer it for large random-access data. Small sequential reads stay simpler with fread — mmap shines where access is sparse, huge, or shared between processes.
Map, then index
mmap returns a pointer to file contents — read and write it like memory; the kernel handles paging invisibly.
Shared vs private
MAP_SHARED writes persist to the file and other mappers; MAP_PRIVATE gives copy-on-write scratch invisible elsewhere.
Unmap to release
munmap(p, len) releases the mapping (flushing shared writes) — leaked mappings linger until process exit.
Mind the failure modes
MAP_FAILED signals errors; accessing past a shrunk file raises SIGBUS — size files deliberately before mapping.
#include <stdio.h>#include <sys/mman.h>#include <fcntl.h>#include <unistd.h> int main(void) { int fd = open("data.bin", O_RDONLY); if (fd < 0) return 1; char *p = mmap(NULL, 5, PROT_READ, MAP_PRIVATE, fd, 0); if (p == MAP_FAILED) return 1; printf("%.5s\n", p); munmap(p, 5); close(fd); return 0;}Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Practice what you learned
Re-implement each visualized algorithm in C yourself — building beats watching.