This is my test code:
#include <cstdio>
struct A {
int a;
int b;
int c __attribute__((aligned(4096)));
int d;
}t;
int main()
{
printf("%d\n",sizeof(t));
return 0;
}
The result is 8192, but I can't figure out the reason.
__attribute__((packed)) variable attribute The packed variable attribute specifies that a variable or structure field has the smallest possible alignment. That is, one byte for a variable, and one bit for a field, unless you specify a larger value with the aligned attribute.
The sizeof for a struct is not always equal to the sum of sizeof of each individual member. This is because of the padding added by the compiler to avoid alignment issues. Padding is only added when a structure member is followed by a member with a larger size or at the end of the structure.
The aligned type attribute allows you to override the default alignment mode to specify a minimum alignment value, expressed as a number of bytes, for a structure, class, union, enumeration, or other user-defined type created in a typedef declaration.
This attribute, attached to struct or union type definition, specifies that each member (other than zero-width bitfields) of the structure or union is placed to minimize the memory required. When attached to an enum definition, it indicates that the smallest integral type should be used.
There are a few facts about alignment in structs that are worth mentioning:
So, since one of these members has an alignment of 4096, the alignment of the struct itself is at least 4096. It will most likely be exactly that.
But since it needs a padding of 4080 bytes before c
, the size of the struct is at least 4104, but it must be a multple of 4096, its alignment. So it grows to 8192.
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