Learn C
#include "systems/mmap.h"

Memory-Mapped Files with mmap in C

#concept

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.

#how it works
1

Map, then index

mmap returns a pointer to file contents — read and write it like memory; the kernel handles paging invisibly.

2

Shared vs private

MAP_SHARED writes persist to the file and other mappers; MAP_PRIVATE gives copy-on-write scratch invisible elsewhere.

3

Unmap to release

munmap(p, len) releases the mapping (flushing shared writes) — leaked mappings linger until process exit.

4

Mind the failure modes

MAP_FAILED signals errors; accessing past a shrunk file raises SIGBUS — size files deliberately before mapping.

#example
#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;
}
Output
hello
1open yields a descriptor; mmap projects the first five bytes into memory with read-only private mapping.
2The %.5s print reads mapped memory like an array — no read() call executed.
3munmap releases the projection and close drops the descriptor — hello printed straight from the page cache.
#use cases
Random access into huge files without read/seek call overhead
Shared-memory IPC between processes via MAP_SHARED
Loading models and datasets with zero-copy paging
Sizing files before mapping to avoid SIGBUS surprises

Recommended resourcesAffiliate links · may earn us a commission

Recommended for learners

Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Pro code editor & AI assistantWrite, debug and explain code faster while you practice the patterns here.Try it free Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books

Practice what you learned

Re-implement each visualized algorithm in C yourself — building beats watching.