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

The munmap function

The munmap function

What you'll learn: How to properly release memory mappings back to the operating system to prevent system-level leaks.

In previous lessons, we looked at how mmap requests a direct slice of memory from the operating system. However, memory is a finite resource. If your program keeps asking for pages of memory without ever returning them, you’ll eventually run the system dry. This is where munmap comes in.

Returning the Borrowed Space

Think of mmap like checking out a reference book from a library. The library (the OS) gives you a specific copy to use. When you are done with it, you shouldn't just leave it on your desk; you need to return it so other patrons (processes) can use it.

The munmap function is the "return" desk. It tells the kernel, "I am finished with this specific range of addresses; you can have them back."

The Syntax

To unmap memory, you need two pieces of information: where the memory starts and how much of it you are giving back.

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

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

    // 1. Request memory
    void *ptr = mmap(NULL, size, PROT_READ | PROT_WRITE, 
                     MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);

    if (ptr == MAP_FAILED) {
        return 1;
    }

    // ... Use the memory for your tasks ...

    // 2. Release memory
    // munmap returns 0 on success, -1 on failure
    if (munmap(ptr, size) == -1) {
        // Handle error
        return 1;
    }

    return 0;
}

Precision Matters

Unlike the standard free() function, which only needs a pointer, munmap requires the exact length of the mapping. This is because mmap works at the "page level."

If you mapped 8192 bytes (two pages), you can actually unmap just one of those pages if you no longer need it, while keeping the other. However, in most day-to-day programming, you will unmap exactly what you allocated. If you pass an incorrect length or a pointer that wasn't returned by mmap, the operating system will likely throw an error, as you are trying to return "books" that don't belong to you.

Once you call munmap, the address becomes invalid. If you try to access ptr again, your program will crash with a Segmentation Fault because that "address space" no longer exists for your process.

Key takeaway

The munmap function releases a specific range of memory pages back to the operating system, requiring both the starting address and the exact size of the region.