Reputation: 30833
How does posix_memalign with alignment size of 4096 bytes differ from mmap
? Does it internally use mmap
or some other mechanism?
Upvotes: 1
Views: 2360
Reputation: 1284
From the standards (POSIX) point of view, posix_memalign()
doesn’t really have any connection to mmap()
:
posix_memalign
- aligned memory allocationThe
posix_memalign()
function shall allocate size bytes aligned on a boundary specified by alignment, and shall return a pointer to the allocated memory inmemptr
.
mmap
- map pages of memoryThe
mmap()
function shall establish a mapping between an address space of a process and a memory object.The
mmap()
function shall be supported for the following memory objects:Support for any other type of file is unspecified.
In particular, POSIX does not specify the MAP_ANONYMOUS
flag that can be used (e. g. on Linux) to use mmap()
to allocate memory without a corresponding file. So, a priori, the two functions perform unrelated tasks: posix_memalign()
allocates dynamic memory (which POSIX mmap()
cannot do), while mmap()
maps files into the process address space (which posix_memalign()
cannot do, as stated in jørgensen’s answer).
When talking about systems which support MAP_ANONYMOUS
, such as Linux (which was tagged in the question), mmap()
gains a capability similar to posix_memalign()
, although mmap()
will return a pointer aligned to the system page size, while posix_memalign()
can be used to obtain memory with a different alignment as well.
Finally, memory allocated with posix_memalign()
is freed using free()
, while mmap()
is cleaned up using munmap()
.
Upvotes: 1
Reputation: 10579
How does posix_memalign with alignment size of 4096 bytes differ from mmap?
The obvious answer: posix_memalign cannot mmap arbitrary files by fd. :)
As for allocation behavior of posix_memalign vs. mmap(MAP_ANOYMOUS): I see no requirement that posix_memalign(size) has to use mmap. It could as well share the sbrk mechanism with/from malloc and return you a properly-aligned pointer to part of the brk area.
Upvotes: 2
Reputation: 363817
posix_memalign
is a higher-level API than mmap
, designed to interoperate with malloc
, free
and realloc
. mmap
usage is more complicated because it offers more functionality than posix_memalign
(mapping files into a process's address space). How it is implemented (in terms of mmap
or otherwise) is left unspecified by the POSIX standard.
Use posix_memalign
where you'd use malloc
if you didn't have alignment restrictions.
Upvotes: 6
Reputation: 30449
Where mmap
is available, posix_memalign
is usually implemented using mmap
. The main difference is that posix_memalign
is in stdlib.h, where as mmap
is a system call which might not be available and have different semantics on different platforms.
Upvotes: 1