How to check if a pointer points to a properly aligned memory location?

If the remainder isn’t zero when dividing the address with the desired alignment, then the address isn’t aligned. inline bool is_aligned(const void * ptr, std::uintptr_t alignment) noexcept { auto iptr = reinterpret_cast<std::uintptr_t>(ptr); return !(iptr % alignment); } Ths can’t be constexpr though, because of the cast. Also, this relies on the implementation-defined fact that the … Read more

When extending a padded struct, why can’t extra fields be placed in the tail padding?

Short answer (for the C++ part of the question): The Itanium ABI for C++ prohibits, for historical reasons, using the tail padding of a base subobject of POD type. Note that C++11 does not have such a prohibition. The relevant rule 3.9/2 that allows trivially-copyable types to be copied via their underlying representation explicitly excludes … Read more

aligned malloc() in GCC?

Since the question was asked, a new function was standardized by C11: void *aligned_alloc(size_t alignment, size_t size); and it is available in glibc (not on windows as far as I know). It takes its arguments in the same order as memalign, the reverse of Microsoft’s _aligned_malloc, and uses the same free function as usual for … Read more

Why is integer assignment on a naturally aligned variable atomic on x86?

“Natural” alignment means aligned to its own type width. Thus, the load/store will never be split across any kind of boundary wider than itself (e.g. page, cache-line, or an even narrower chunk size used for data transfers between different caches). CPUs often do things like cache-access, or cache-line transfers between cores, in power-of-2 sized chunks, … Read more

Does alignment really matter for performance in C++11?

Alignment matters not only for performance, but also for correctness. Some architectures will fail with an processor trap if the data is not aligned correctly, or access the wrong memory location. On others, access to unaligned variables is broken into multiple accesses and bitshifts (often inside the hardware, sometimes by OS trap handler), losing atomicity. … Read more

Do class/struct members always get created in memory in the order they were declared?

C99 §6.7.2.1 clause 13 states: Within a structure object, the non-bit-field members and the units in which bit-fields reside have addresses that increase in the order in which they are declared. and goes on to say a bit more about padding and addresses. The C89 equivalent section is §6.5.2.1. C++ is a bit more complicated. … Read more