Using mmap for large allocations
What you'll learn: How to bypass the standard heap and request large chunks of memory directly from the operating system using mmap.
The "Supermarket" vs. the "Warehouse"
When you use malloc, you are shopping at a local supermarket. It’s convenient for small items (like an int or a small struct), but the supermarket has overhead and limited stock. If you need ten thousand crates of milk, you don't go to the store; you call the warehouse directly.
In C, mmap is your direct line to the warehouse (the Operating System). Instead of carving space out of the program's heap, mmap asks the OS to map a specific number of pages of physical memory directly into your application's address space.
Why use mmap?
For very large allocations (typically anything over 128 KB), malloc often calls mmap behind the scenes anyway. By using it manually, you gain:
- Efficiency: Large blocks are allocated on "page boundaries," making them faster for the CPU to process.
- Immediate Release: When you "unmap" memory, it is returned to the OS immediately, whereas
free()might keep memory held in the heap for later reuse. - Zero-filling: The OS automatically provides memory cleared with zeros for security reasons.
Basic Usage
To use mmap for anonymous memory (memory not linked to a file), you need to provide several flags.
#include <sys/mman.h>
#include <stdio.h>
#include <unistd.h>
int main() {
size_t size = 4096; // Usually the size of one memory page
// Requesting memory:
// PROT_READ | PROT_WRITE: We want to read and write
// MAP_ANONYMOUS | MAP_PRIVATE: Not a file, and just for this process
void* ptr = mmap(NULL, size, PROT_READ | PROT_WRITE,
MAP_ANONYMOUS | MAP_PRIVATE, -1, 0);
if (ptr == MAP_FAILED) {
perror("mmap");
return 1;
}
// Use it like any array
int* data = (int*)ptr;
data[0] = 42;
// Return it to the warehouse
if (munmap(ptr, size) == -1) {
perror("munmap");
}
return 0;
}
When to use it
Avoid mmap for small variables; the overhead of talking to the OS is too high for a single integer. Use it when you are building custom database buffers, large cache systems, or handling massive data arrays that exceed several megabytes.
Key takeaway
Use mmap to request large, page-aligned blocks of memory directly from the OS, bypassing the heap's management overhead.