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!
I just released Vidrio, a free app for macOS and Windows to make your screen-sharing awesomely holographic. Vidrio shows your webcam video on your screen, just like a mirror. Then you just share or record your screen with Zoom, QuickTime, or any other app. Vidrio makes your presentations effortlessly engaging, showing your gestures, gazes, and expressions. #1 on Product Hunt. Available for macOS and Windows.

With Vidrio

With generic competitor

More by Jim

Tagged . All content copyright James Fisher 2017. This post is not associated with my employer. Found an error? Edit this page.