This question is related to How to ensure a member is 4-byte aligned?
Example:
struct Aligned
{
char c;
__attribute__((__aligned__(4))) int32_t member;
}
struct Test
{
char c;
Aligned s;//is s.member 4 bytes aligned?
}
void f1()
{
char c1;
Aligned s;//is s.member 4 bytes aligned?
char c2;
}
void f2()
{
Aligned* s = new Aligned();//is s.member 4 bytes aligned?
}
Can you please explain if “member” is 4 bytes aligned in all cases, and if yes how this works?
Edit:
I forgot the case where Aligned is derived from other struct:
struct Aligned : public SomeVariableSizeStruct
{
char c;
__attribute__((__aligned__(4))) int32_t member;
}
Second Edit: My questions is: is always first member of a structure 4 bytes aligned? Because in all cases presented here the first variable address might not be 4 bytes aligned and the 3 bytes padding doesn’t guarantee that “member” is 4 bytes aligned
Yes, it works. The compiler is required to make it work.
Every type has an alignment which the compiler has to respect. You’ve specified that one particular object should use 4-byte alignment, but every other object, a
char, anint, astd::stringand anything else also have their own alignment requirements.So the compiler is used to having to cope with this.
To determine the alignment required for
Aligned, the compiler basically goes through all its members (as well as its base class(es) to find the one that requires the strictest alignment. This then becomes the alignment required forAlignedas well.The most aligned member in this case is
member, which requires 4-byte alignment. SoAlignedrequires 4-byte alignment.And yes, this is guaranteed whether you create an
Alignedon the stack as a function local variable, or as another class member, or on the heap withnew.