How to get page-aligned memory from new or malloc operator for mremap

Is there a way to allocate a block of memory so that its start address is aligned with a given page size? Note that I do not want to calculate the aligned address after allocating the block. The reason is that at some point I will need to call mremap () in a block: mremap requires that the old address argument align to the page.

+4
source share
3 answers

You need to use alloocation system programs, which are not a huge deal, as you also use the system-dependent mremap function. However, you also need to be careful what you place in memory (for example, using placement new will not work well), because mremap can change the memory address when resizing.

Since you are most likely using Linux to do this, have you considered the anonymous mmap region? This will behave just like malloc, except that it is automatically paged.

+1
source

mremap can only be used safely in memory areas allocated by mmap , which are essentially page-aligned. Using it otherwise is dangerous (formally, undefined behavior) and may seem to work, but it will probably upset things in ways that you won’t see right away.

+2
source

Some malloc packages provide this feature, but are not standardized.

posix version

+1
source

Source: https://habr.com/ru/post/1484041/


All Articles