Search code examples
c++alignmentalignof

How to tell the maximum data alignment requirement in C++


Referencing this question and answer Memory alignment : how to use alignof / alignas? "Alignment is a restriction on which memory positions a value's first byte can be stored." Is there a portable way in C++ to find out the highest granularity of alignment that is required for instructions not to fault (for example in ARM)? Is alignof(intmax_t) sufficient since its the largest integer primitive type?

Further, how does something in malloc align data to a struct's boundaries? For example if I have a struct like so

alignas(16) struct SomethingElse { ... };

the SomethingElse struct is required to be aligned to a boundary that is a multiple of 16 bytes. Now if I request memory for a struct from malloc like so

SomethingElse* ptr = malloc(sizeof(SomethingElse));

Then what happens when malloc returns a pointer that points to an address like 40? Is that invalid since the pointer to SomethingElse objects must be a multiple of 16?


Solution

  • You might be looking for std::max_align_t