I have the following Nested structure in C. (64 bit)
typedef struct {
int a;
int b;
int c;
struct {
int ab;
long bc;
}
int d;
} Test;
I see that,
a = 4 bytes
b = 4 bytes
c = 4 bytes
padding1 = 4 bytes
inner structure = 16 bytes ( 4 bytes for ab, 4 bytes padding, 8 bytes for bc)
d = 4 bytes
padding2 = 4 bytes
sizeof(Test) returns 40 bytes.
My questions:
padding1 -> why is this 4 bytes? Is this because the inner structure itself should be aligned ?. ( Also, Is it aligned with 8 byte (long) or 16 byte (size of inner) boundary.? )
padding2 -> Is this 4 byte padding because of max of alignment done inside the structure (which is 8) ??
Thanks,
Personally, I think no matter the program is 32-bit or 64-bit , the size of structure should always be 16 bytes (since char is 1 byte long, and the alignment of double is 8 bytes).
Structure Padding in C:The structure padding is automatically done by the compiler to make sure all its members are byte aligned. The size of the below structure is 16 bytes due to structure padding: Struct dummy { Char ch; Int num; Double temp; }
In Structure, sometimes the size of the structure is more than the size of all structures members because of structure padding. Note: But what actual size of all structure member is 13 Bytes. So here total 3 bytes are wasted. So, to avoid structure padding we can use pragma pack as well as an attribute.
The answer to that lies in how a CPU accesses memory. Typically a CPU has alignment constraints, e.g. a CPU will access one word at a time, or a CPU will require data to be 16byte aligned, etc. So to make sure that data is aligned according to the constraints of the CPU, padding is required.
- padding1 -> why is this 4 bytes? Is this because the inner structure itself should be aligned ?. ( Also, Is it aligned with 8 byte (long) or 16 byte (size of inner) boundary.? )
It's because the inner struct
should be 8-byte aligned, so that the long
can reliably be 8-byte aligned.
- padding2 -> Is this 4 byte padding because of max of alignment done inside the structure (which is eight) ??
It is there so that the size of the entire struct
is a multiple of eight bytes, so that the inner struct
can be suitably aligned on an eight-byte boundary.
In this particular case, the alignment requirements could be met with just four bytes of padding if an anonymous struct
member could be treated differently from a free-standing struct
, but 6.7.2.1
14 Each non-bit-field member of a structure or union object is aligned in an implementation-defined manner appropriate to its type.
forbids that. So to reduce the size of the struct
, the programmer needs to rearrange it, move an odd number of int
members past the inner struct
(or make int ab;
and long bc;
direct members of Test
without going through an anonymous struct
).
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