Reputation: 764
My Compiler require me to have a memory aligned structure declaration, to ensure proper data access. I have a top structure, which comprised of some other structures. Is it sufficient to ensure that the top structure to be aligned to 32 byte boundary or I need to ensure that each structure should be aligned to 32 byte boundary. Code snippet is below:-
typedef struct {
int p;
int q;
char n;
} L;
typedef struct {
int c;
int d;
char e;
L X2[13];
} B;
typedef struct {
int a;
int b;
B X1[10];
} M;
To ensure correct data access, Do I need to ensure that all structures are memory aligned properly, or padding the top most structure will ensure memory alignment.
Upvotes: 2
Views: 1069
Reputation: 2011
If you want to use natural alignment you have to order the fields and pad manually to the natural word size. Portability is not guaranteed but for a specific processor this can be done (not uncommon in the embedded world). If sizeof(int) is 4 you have to add padding to your sub-structs to ensure alignment in the arrays (I assume that your goal is to avoid "secret" padding added by the compiler?). For example :
typedef struct {
int p;
int q;
char n;
char pad[3];
} L;
typedef struct {
int c;
int d;
char e;
char pad[3];
L X2[13];
} B;
typedef struct {
int a;
int b;
B X1[10];
} M;
would normally cause no "hidden" alignment in the structures.
Upvotes: 0
Reputation: 1400
If you can use it, C11 has alignment statements if your application (or architecture, or performance) needs it : http://en.wikipedia.org/wiki/C11_%28C_standard_revision%29
GCC surely has extensions also.
Upvotes: 0
Reputation: 93476
Sometimes your application may require specific layout, but if as you say in this case it is a requirement of your compiler (or probably more accurately the target architecture of your compiler), then it is the compiler's responsibility to ensure those requirements are met.
If you require alignment other than that which the compiler will enforce naturally as required by the target, you will need compiler specific directives for packing and alignment; however applying such directives and getting it wrong is far more likley to cause an alignment fault than letting the compiler handle it. If you attempt to align by adding your own padding members, it may work, but is unnecessary and the compiler may insert additional padding of its own too.
The point is the compiler will not generate a structure with members it cannot safely and efficiently address. It will insert any necessary padding between members to ensure that subsequent members are addressable.
If you don't believe it will work, get your linker to output a map file (if it does not do so already) and check the address of these symbols to verify correct alignment. Also look at the generated size of the structures; you may find that some of them are larger than the sum of their parts - that is the compiler forcing alignment by inserting padding.
Upvotes: 2