What is mmap in C?

The functions malloc, free and friends are not system calls. They are library functions. Under the hood, the system calls they use are mmap and munmap. (Older implementations use brk or brk; I’ll cover that in future.)

The mmap syscall lets the program manipulate virtual memory. The address space is divided into a number of pages. (On my machine, each page is 4096 bytes long.) Each page can be mapped to some underlying resource. Here, we use mmap to map a page of virtual address space to a block of hardware memory. (mmap can also map the page to a file, which can be a much more convenient interface to file manipulation.)

Here’s an example:

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

int main(void) {
  size_t pagesize = getpagesize();

  printf("System page size: %zu bytes\n", pagesize);

  char * region = mmap(
    (void*) (pagesize * (1 << 20)),   // Map from the start of the 2^20th page
    pagesize,                         // for one page length
    PROT_READ|PROT_WRITE|PROT_EXEC,
    MAP_ANON|MAP_PRIVATE,             // to a private block of hardware memory
    0,
    0
  );
  if (region == MAP_FAILED) {
    perror("Could not mmap");
    return 1;
  }

  strcpy(region, "Hello, world!");

  printf("Contents of region: %s\n", region);

  int unmap_result = munmap(region, 1 << 10);
  if (unmap_result != 0) {
    perror("Could not munmap");
    return 1;
  }
  // getpagesize
  return 0;
}

This prints:

% ./a.out
System page size: 4096 bytes
Contents of region: Hello, world!
Tagged #system-calls, #memory-management, #c, #programming.

Similar posts

More by Jim

👋 I'm Jim, a full-stack product engineer. Want to build an amazing product and a profitable business? Read more about me or Get in touch!

This page copyright James Fisher 2017. Content is not associated with my employer. Found an error? Edit this page.