Search code examples
cwindowsmemoryalignmentpadding

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:

  • the red area is member1
  • the blue area is member2
  • the green area is member3
  • the yellow area marks the location of dbl1 within member3

memory-layout


Constraints

  • Compiler is VS2012
  • the actual stucture of other_struct should not matter here, it's a 40-byte sized 4-byte aligned structure
  • I do not want any workarounds for the behavior (reordering, packing, ...) but an explanation why this is happening.

Solution

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