Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use __attribute__((aligned())) in struct, why the result of sizeof is this?

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.

like image 714
hexiecs Avatar asked Jul 26 '16 09:07

hexiecs


People also ask

What does __ Attribute__ packed )) Meaning?

__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.

What is the relationship between the result of sizeof () for a structure variable and the sum of the sizeof () calls across the same structure's members?

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.

What does attribute aligned do?

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.

What is a struct attribute?

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.


1 Answers

There are a few facts about alignment in structs that are worth mentioning:

  1. The size of a type is always a multiple of its alignment.
  2. The alignment of a struct is always a multiple of the alignment of all its members.

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.

like image 111
rodrigo Avatar answered Nov 16 '22 01:11

rodrigo