Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 403
Curious Avatar asked Feb 15 '17 20:02

Curious


People also ask

What does mmap return?

Return Value Upon successful completion, the mmap() function returns the address at which the mapping was placed; otherwise, it returns a value of MAP_FAILED, which has a value of 0, and sets errno to indicate the error.

What is an aligned pointer?

Aligned Pointer means that pointer with adjacent memory location that can be accessed by a adding a constant and its multiples. for char a[5] = "12345"; here a is constant pointer if you and the size of char to it every time you can access the next chracter that is, a +sizeofchar will access 2.

Is mmap persistent?

mmap'd memory is not persistent between application executions (unless it is backed by a file).

Do you have to call munmap?

munmap happens automatically on exit So if the program is going to exit anyways, you don't really need to do it. man munmap 4.15 says: The munmap() system call deletes the mappings for the specified address range, and causes further references to addresses within the range to generate invalid memory references.


1 Answers

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.

like image 137
Anty Avatar answered Oct 05 '22 10:10

Anty