CC Explainer
C · 6 · Advanced / Job-Ready32 / 35 · 91%

mmap & Shared Memory

Map a file or anonymous pages straight into your address space.

Examples: mmap, munmap, MAP_SHARED, shm_open

shortcuts: ← prev · → next · M mark
1

Mapping a File

Read the file as if it were an array — no read() loop.

Example
example
int fd = open("data.bin", O_RDONLY);
struct stat st; fstat(fd, &st);
char *p = mmap(NULL, st.st_size, PROT_READ, MAP_PRIVATE, fd, 0);
if (p == MAP_FAILED) { perror("mmap"); return 1; }

// p[0] .. p[st.st_size - 1] are the file bytes
munmap(p, st.st_size);
close(fd);
2

Anonymous Memory

malloc uses this under the hood for large allocations.

Example
example
void *big = mmap(NULL, 64u << 20,
                 PROT_READ | PROT_WRITE,
                 MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
Stackgrows down ↓Heapgrows up ↑BSSuninitialisedDatainitialised globalsTextcode / read-only
mapped region between heap and stack
3

Shared Between Processes

MAP_SHARED makes writes visible to every process mapping the same object.

Example
example
int fd = shm_open("/myshm", O_CREAT | O_RDWR, 0600);
ftruncate(fd, size);
void *p = mmap(NULL, size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
// synchronize with a process-shared mutex or atomics
4

Trade-offs

mmap is not always faster.

Common pitfalls
  • ✕Page faults on first touch — random access to a cold mapping can be slower than a sequential read().
  • ✕Accessing past the file end raises SIGBUS, not EOF.
  • ✕Mappings survive fork() with MAP_SHARED and are copied with MAP_PRIVATE.
  • ✕Always munmap; mappings are not freed by free().