c++alignmentmmap

Does mmap return aligned pointer values


Does mmap() guarantee that the return values are aligned to the largest alignment on the system? i.e. is it guaranteed by the POSIX standard that mmap has to return pointer values that are multiples of alignof(std::max_align_t)?

I was not able to find this information on either the Ubuntu linux mmap(2) man page or a mac osx mmap(2) man page


Solution

  • Yes it does.

    http://man7.org/linux/man-pages/man2/mmap.2.html

    In case of most "popular" NULL mapping

    If addr is NULL, then the kernel chooses the address at which to create the mapping; this is the most portable method of creating a new mapping. If addr is not NULL, then the kernel takes it as a hint about where to place the mapping; on Linux, the mapping will be created at a nearby page boundary. The address of the new mapping is returned as the result of the call.

    Even if you specify MAP_FIXED then

    Don't interpret addr as a hint: place the mapping at exactly that address. addr must be a multiple of the page size. If the memory region specified by addr and len overlaps pages of any existing mapping(s), then the overlapped part of the existing mapping(s) will be discarded. If the specified address cannot be used, mmap() will fail. Because requiring a fixed address for a mapping is less portable, the use of this option is discouraged.

    Taking the fact the smallest page is 4096B (for x86, but for other platforms it is multiple of 1024B anyway) and as std::max_align_t is most likely to be 16B on 64bit systems it will be aligned.