eckes
eckes

Reputation: 67177

Why does my structure element carry padding bytes?

I have a confusing behaviour with the memory alignment of structure elements. Consider these two structures:

typedef struct s_inner {
    unsigned long ul1;
    double        dbl1;
    fourth_struct s4;
    unsigned long ul2;
    int           i1;
} t_inner;

typedef struct s_outer {
    other_struct    member1; /* 4-byte aligned, 40 bytes in terms of sizeof() */
    unsigned long   member2;
    t_inner         member3; /* see above */
} t_outer;

When I inspect the memory layout of t_outer, I could see that the elements of member1 are 4-byte aligned, just as I would expect it. Also the memory layout of member3 is as expected: ul1 has 4 padding bytes attached so that dbl1 is aligned on an 8-byte border (normal on Win32).

However, when I inspect the memory layout of member2, I could see that this member has 4 padding bytes attached to it. Could anyone explain why on earth member2 receives padding bytes? My expectation was that member2 does not carry a padding.


Edit 1: See this memory dump. Before filling the structure elements, I've memset'd the whole t_outer structure with p's:

memory-layout


Constraints

Upvotes: 1

Views: 206

Answers (2)

John Bollinger
John Bollinger

Reputation: 181824

The VS2012 docs describe its padding behavior. In particular, they specify that the alignment requirement for a struct is the largest alignment requirement of any of its members. Member member3's type t_inner has a member of type double, with an 8-byte alignment requirement, therefore member3 overall has an 8-byte alignment requirement (and, also, t_outer has an 8-byte alignment requirement). Padding is required between member2 and member3 to obtain 8-byte alignment of member3.

Upvotes: 2

Hans Passant
Hans Passant

Reputation: 942408

so that dbl1 is aligned on an 8-byte border

Sure. But that alignment guarantee means bupkis if the structure itself is not aligned to 8 as well. Which is a guarantee that's normally provided by the compiler's address choices for the data section and the stack frame. Or the memory allocator. All guarantee at least alignment to 8.

But when you embed the structure inside s_outer then those 4 bytes of padding before member3 (not after member2) are required to get the alignment guarantee back.

Also note that a structure can have padding after the last member. Which may be required to ensure that members are still aligned when the structure is stored in an array. Same reason.

Upvotes: 2

Related Questions