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

RSS
EMAIL
FACEBOOK
FACEBOOK
GOOGLE
GOOGLE
https://www.poftut.com/mmap-tutorial-with-examples-in-c-and-cpp-programming-languages/
PINTEREST
PINTEREST
INSTAGRAM

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.

Library

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

Syntax

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.

Example

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 Get Ram Size In Linux?

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

LEARN MORE  Compiling C and C++ Applications with GCC

mmap() Example
mmap() Example

RSS
EMAIL
FACEBOOK
FACEBOOK
GOOGLE
GOOGLE
https://www.poftut.com/mmap-tutorial-with-examples-in-c-and-cpp-programming-languages/
PINTEREST
PINTEREST
INSTAGRAM