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

Want to build a fantastic product using LLMs? I work at Granola where we're building the future IDE for knowledge work. Come and work with us! Read more or get in touch!

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