I have a structure where the members have certain alignment requirements while no such requirement exist for the structure itself.
I’m using gcc so using __attribute__((aligned(n))) will do the trick, unless (as far as I know) an instance of the struct is allocated on the heap.
How do I keep the alignment for heap allocated instances? posix_memalign(3) will align the structure itself, but not the structure members, so I can’t see how to make it work with that function.
The source is here: https://github.com/colding/disruptorC/blob/master/src/disruptor.h#L92
No matter where a struct is—stack or heap—the layout of the struct must be the same. The compiler ensures that the
sizeof()and the layout of elements within the struct match the alignment requirements (via padding). It also gives the struct itself a required alignment so that its members end up on the right boundary (this value is the largest alignment of any of its members).So just use
posix_memalignand you’ll be fine:For example, if you have this definition:
It’s compiler-dependent, of course, but the most likely behavior is that the compiler lays out the following:
and gives the whole thing an alignment of 8 bytes. Then, if the struct itself is aligned properly (on an 8-byte boundary), the double that’s 8 bytes offset into it will also be properly aligned.
(
alignofis different in different compilers/standards:__alignof__in gcc,__alignofin MSVC, andalignofin C11/C++11.)