13

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

Curious
  • 20,870
  • 8
  • 61
  • 146
  • I don't know if it's guaranteed, but since it's backed by hardware capabilities I'd be extremely surprised if it didn't. – Mark Ransom Feb 15 '17 at 20:42
  • [this link](http://stackoverflow.com/questions/31411730/mmap-enforce-64k-alignment) might help. Quoated: In contrast address returned by mmap is only guaranteed to be page-aligned. – felix Feb 15 '17 at 20:43
  • @felix The man page for `munmap()` says `The addr parameter was not page aligned (i.e., a multiple of the page size).`, meaning that I cannot deallocate memory that is not aligned on a page boundary, and since the page boundary is larger than the maximum alignment, I will not be able to call `munmap()` in the case where a pointer is not aligned on the maximum alignment – Curious Feb 15 '17 at 20:51

1 Answers1

14

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 than

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 alligned.

Anty
  • 1,486
  • 1
  • 9
  • 12
  • 1
    This holds if you provide a zero offset. If you provide a misaligned offset, you will get a misaligned address (ie, odd offset will give you an odd address). This was observed on Linux. – goertzenator Jan 21 '22 at 19:47
  • How can you provide a misaligned offset? `offset` is a multiple of PAGE_SIZE, therefore 4096B. But we can provide a misaligned `addr`. – Alexis Feb 24 '22 at 11:17