memory alignment higher than maximum alignment alignas malloc

443 Views Asked by At

How would one go about using malloc (or new, since on most implementations new is implemented with malloc, not sure what the standard says about alignment and new other than data has to be aligned with the highest scalar alignment) with a type that has an alignment requirement set to being higher than the maximum alignment requirement on the system (alignof(std::max_align_t))? So something like

alignas(alignof(std::max_align_t) + alignof(int)) struct Something {
    ...
};
1

There are 1 best solutions below

0
On

Turning a comment into an answer.

Let ALIGNMENT denote the required alignment.

Then you can safely allocate your structure as follows:

char* buffer = new char[ALIGNMENT+sizeof(Something)];
uintptr_t address = reinterpret_cast<uintptr_t>(buffer);
uintptr_t aligned_address = address+ALIGNMENT-address%ALIGNMENT;
Something* something = reinterpret_cast<Something*>(aligned_address);