The only think that I know (so maybe it is not the best choice) is to use mmap
for Linux. There were some situations when I had to allocate huge memory chunks aligned to specific values, so I used it (because here you can specify the address and the length of the memory chunk) but it requires to implement some memory manager unit since now you are going to manage the allocations (and releases).
void *mmap(void *addr, size_t length, int prot, int flags, int fd, off_t offset);
Look here for details: http://man7.org/linux/man-pages/man2/mmap.2.html
To make it not mapped to any file just set flags
to MAP_ANONYMOUS
:
MAP_ANONYMOUS
The mapping is not backed by any file; its contents are
initialized to zero. The fd and offset arguments are ignored;
however, some implementations require fd to be -1 if
MAP_ANONYMOUS (or MAP_ANON) is specified, and portable
applications should ensure this. The use of MAP_ANONYMOUS in
conjunction with MAP_SHARED is supported on Linux only since
kernel 2.4.
If addr
is NULL then the system will pick for you the available address but since you want to allocate it above the 2G you will need to manage a list of allocated pages in order to know which addresses are used above the 2G. Note also that if you specify that addr=X
, and mmap
will not be able to use this address it won't fail, it just will pick another address which can be used without any failure indication (except for the fact that the returned pointer will not be equal to addr
). However you can use MAP_FIXED
flag to enforce the address you supply and if mmap
won't be able to use it, it will fail (return MAP_FAILED
).
MAP_FIXED
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.
EDIT
NOTE that using MAP_FIXED
is not recommended since as the description says
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.
and you will not even know about it. Safer to check that addr
is equal to the returned by mmap
address.