Course contentsShow
← C
Lesson 594 of 1,2198. Memory ManagementFree lesson

Anonymous memory mappings

Anonymous memory mappings

What you'll learn: How to request raw memory blocks directly from the Operating System without using a file as a back-end.

In earlier lessons, you learned about malloc(). While malloc is great for small objects, it is actually a middleman. When you need a massive chunk of memory—say, several megabytes for a custom database buffer—it is often more efficient to talk directly to the Operating System using mmap().

Memory without a file

The name mmap stands for "memory map." Usually, this function is used to map a file on your hard drive into your program's memory. However, when we use the MAP_ANONYMOUS flag, we tell the OS: "Give me a block of RAM that isn't connected to any file."

Think of it like renting a storage unit. Standard file mapping is like renting a unit to organize the boxes you already have. Anonymous mapping is like renting an empty unit just to have the open floor space to build something new from scratch. Because there is no file involved, the OS simply zeroes out the RAM and hands you the keys.

How to use mmap

To create an anonymous mapping, we use mmap() with specific arguments. We set the file descriptor to -1 and the offset to 0 because there is no file to point to.

#include <stdio.h>
#include <sys/mman.h>
#include <unistd.h>

int main() {
    size_t size = 4096; // Usually one "page" of memory

    // Requesting anonymous memory
    // PROT_READ | PROT_WRITE: We want to read and write to it
    // MAP_PRIVATE | MAP_ANONYMOUS: Private to this process, not a file
    void *ptr = mmap(NULL, size, PROT_READ | PROT_WRITE, 
                     MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);

    if (ptr == MAP_FAILED) {
        perror("mmap");
        return 1;
    }

    // Use it like an array
    int *array = (int *)ptr;
    array[0] = 42;
    printf("Value at index 0: %d\n", array[0]);

    // Clean up
    munmap(ptr, size);
    return 0;
}

Why use this?

System-level programmers use anonymous mappings for two main reasons:

  1. Large Allocations: malloc actually calls mmap under the hood for very large requests.
  2. Page Alignment: mmap always gives you memory aligned to the system's "page size" (usually 4KB), which is a requirement for certain high-performance hardware interactions.

Key takeaway

Anonymous memory mappings provide a way to request large, zero-initialized blocks of RAM directly from the kernel without the overhead of a file.