1

I'm looking at come C code which seems to be allocating memory aligned to the page size:

_aligned_malloc( size, PAGESIZE )

where PAGESIZE is a variable set to 4096. For the moment ignoring that page size could have a value different from 4096, I just want to know why one would want to align the memory allocation to the page size. What performance benefits does it provide, if any? Could it have any other purpose than performance?

G S
  • 35,511
  • 22
  • 84
  • 118
  • 3
    Shared memory prefers whole pages. Also changing the protection on a block of memory usually involves whole pages. – Paul R Jan 20 '18 at 18:10
  • It might be a good idea to read https://stackoverflow.com/questions/38088732/explanation-to-aligned-malloc-implementation. – Unmanned Player Jan 20 '18 at 20:02

1 Answers1

4

It might be related to paging, and to virtual address space. Page size is related to the MMU so is usually constrained by the hardware.

On some operating systems, some functions or system calls want (i.e. require) a page-aligned pointer. For example, on Linux, mmap(2) (notably when you use it with MAP_FIXED, it wants a genuine page aligned address), mprotect(2), madvise(2), mlock(2), mremap(2), also related shm_overview(7).

Some very low-level IO operations might prefer (e.g. run faster) with page aligned buffers (perhaps send(2), or direct write(2) to some block device...) because the kernel might avoid some block copy (e.g. do some DMA) and could special-case page aligned data.

Basile Starynkevitch
  • 223,805
  • 18
  • 296
  • 547