Search code examples
c++memorymalloccpummap

C++, How to Ensure Aligned Memory Using mmap()?


I am currently allocating memory using mmap like this:

void *void_new_block = mmap(nullptr, size, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);

Now I want to improve performance on 64 bit cpus thus I need my block to reside between addresses which are multiplication of 8 For that I need 2 things:

  1. To ensure that size is a multiplication of 8 (which I already did by rounding it up)

  2. To ensure that mmap will start allocating at an addresses of multiplication of 8.

How may I solve 2? I heard that some special flag might help?

Some Notes, My OS:

Distributor ID: Ubuntu
Description:    Ubuntu 18.04.3 LTS
Release:    18.04
Codename:   bionic

g++ version:

g++ (Ubuntu 7.5.0-3ubuntu1~18.04) 7.5.0
Copyright (C) 2017 Free Software Foundation, Inc.

Solution

  • mmap always allocates entire pages.

    If addr is NULL, then the kernel chooses the (page-aligned) address at which to create the mapping [...] If addr is not NULL, then [...] on Linux, the kernel will pick a nearby page boundary

    (on systems other than Linux, it still has to pick a page boundary, but it might not be nearby)

    On x86 or x86_64, pages are 4096 bytes, so you are fine. It is hard to imagine a CPU with pages smaller than 8 bytes.