Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Equivalent of std::aligned_storage<> in C?

Tags:

c++

c

alignment

c99

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 ;)).

like image 761
Praxeolitic Avatar asked Nov 11 '15 16:11

Praxeolitic


2 Answers

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.

like image 162
zwol Avatar answered Sep 25 '22 06:09

zwol


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.

like image 30
this Avatar answered Sep 24 '22 06:09

this