alligned alloc

Allocate size bytes of uninitialized storage whose alignment is specified by alignment. The size parameter must be an integral multiple of alignment.

1. C

C11

#include <stdlib.h>
void *aligned_alloc( size_t alignment, size_t size );

2. C++

C++17

#include <cstdlib>
void* aligned_alloc( std::size_t alignment, std::size_t size );

3. Why?

malloc/free doesn’t allow to specify the allignment to, for example, page level. It will just align to “alignment requirement” of an object alignof(struct S).

If we wanted alignment to the page level with malloc we would have to allocate extra space, fix by ourselves the initial pointer, and keep track of the original pointer to then deallocate it.

constexpr auto page_size = 4096;

void* allocate_page_boundary(std::size_t size)
{
    // Allocate extra space to guarantee alignment.
    auto memory = std::malloc(page_size + size);

    // Align the starting address.
    auto address = reinterpret_cast<std::uintptr_t>(memory);
    auto misaligned = address & (page_size - 1);

    return static_cast<unsigned char*>(memory) + page_size - misaligned;
}

Source of the code: https://www.foonathan.net/2022/08/malloc-interface/#content