Does mmap always return higher address

2019-03-04 09:23发布

问题:

Does mmap (when called with MAP_ANONYMOUS, that is, for allocating memory) always return higher memory address than a previous call? If not so, Is there any way to make it return a higher address always?

回答1:

By default, mmap can return any address aligned on a page boundary, in any order.

If you want to enforce that the returned address is the one you specify, you can use the MAP_FIXED flag, but that isn't very portable and reliable. This way you are tying your code with the particular implementation of mmap on a particular kernel.

But anyway, why would you always need a higher address than the previous one? Possibly a better way is to change the logic of your program.



回答2:

Not necessarily, at least not according to its definition.

And I would believe that with ASLR it could happen that upper addresses are no more available, so mmap has to choose some lower address range.

Obviously, on 32 bits processors (& kernels) the memory space could be nearly filled, so when asking for a big mmap-ed range the kernel should find one which fits, and that could be anywhere.

If you want a monotone direction, use sbrk (but I really recommend against using it).

Another possibility could be to pre-allocate a very large amount (e.g. several terabytes) of address space using mmap with MAP_NORESERVE at program initialization, and call mmap with MAP_FIXED inside that range again to get the really usable space (in more manageable chunks, e.g. dozens of megabytes).

@MetallicPriest: you really should motivate and explain much more your questions. There are so mysterious and weird (and even I cannot guess all the context) that it is not very fun to answer them.