mmap Tutorial with Examples In C and C++ Programming Languages – POFTUT

mmap Tutorial with Examples In C and C++ Programming Languages

As programmers we generally use malloc() , free() and similar functions in order to allocate memory. They are provided by glibc() library. The actual work is done by mmap() and munmap()which is a Linux systemcall.

What Does mmap() Function?

mmap() function or system call will create a mapping in the virtual meory of the current process.The address space consist of multiple pages and each page can be mapped some resource. We can create this mapping for a resources we want to use.


mmap() and munmap() functions are provided by sys/mman.h library. so in order to use we need to include them like below.


As mmap() provides flexible memory mapping it has a lot of parameters to use.

  • void *addr is the address we want to start mapping
  • size_t lengthint is the size we want to map in as integer
  • PROT_READ|PROT_WRITE|PROT_EXEC options about page
  • MAP_ANON|MAP_PRIVATE options about page

Memory Mapping Types

We have two option about memory mapping for sharing.

  • MAP_SHARED will map given page and this will be also visible by other processes.
  • MAP_PRIVATE will map given page and this will not visible to other processes.


Here is an example which takes a page from start of 2^20 . The default size of the page is 4096 byte so we will map a page with 4096 byte memory.

LEARN MORE  How To Download, Compile and Install Custom Linux Kernel Manually In Ubuntu, Debian, Mint, Kali, CentOS?

When we compile with the following command the a.out executable will be generated.

LEARN MORE  Manage Libraries With ldconfig Command In Linux

mmap() Example

mmap() Example

1 Response

  1. mark says:

    Does not compile

    /usr/include/x86_64-linux-gnu/sys/mman.h:57:14: note: expected ‘__off_t {aka long int}’ but argument is of type ‘void *’

Leave a Reply

Your email address will not be published. Required fields are marked *

Enjoy this blog? Please spread the word :)