In C, is there a way to get over-aligned (i.e. more alignment than can be deduced from the type system) storage on the stack?
For variables in dynamically allocated memory we can always align manually if all else fails but what can be done for variables in automatically allocated memory?
I guess it's possible to use a char[size + alignment - 1]
and then always use bit manipulation to access the variable but this seems a "bit" shadier than necessary (har har har ;)).
In C2011, there are the _Alignas
and _Alignof
keywords, the header <stdalign.h>
which makes their use slightly less ugly, and the type max_align_t
(which is in <stddef.h>
). You can, for instance, write
double _Alignas(4*_Alignof(double)) dvector[16];
to request an array of 16 double
quantities aligned to 4x the usual alignment for double
, as might be necessary for use with CPU-specific vector instructions. This is not guaranteed to work on all implementations, but if it doesn't work it's guaranteed to be a compile-time error.
Prior to C2011 there was no standard way to do this, but many compilers did have extensions with similar functionality, e.g. GCC's __attribute__ (aligned)
construct.
Well unions come to mind.
union This
{
int integer;
align_type alignment;
} ;
There is no padding before members in unions. So if you declare an automatic variable union This
, then it, and all of its members, should be aligned the same as is alignment of the member with the highest alignment.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With