Bechma
Bechma

Reputation: 517

Memory alignment in C-structs under Windows 32bits

Here is a snippet:

struct a {
  float* f;
  char c;
  int i;
  char z[4];
  double d;
  short s;
};

struct b {
   struct a a1;
   int j;
   struct a a2;
};

When I do a printf("%d\n",sizeof(struct a)), it emits to me 32... But when I do the same for the struct b, it emits 72 which I don't know how can be possible this, it should be 32+4+28(padding)+32 following the same calcs that I did to find out the previous result... can anyone tell me why is this happening?

Upvotes: 1

Views: 49

Answers (2)

AlexP
AlexP

Reputation: 4430

Nothing is aligned to more than multiples of 8 for the x86/amd64 architectures. See for example Structure Alignment for Visual Studio. struct a and struct b have a double member, so they must be aligned at a multiple of 8 and their sizeof must be a multiple of 8; you can easily see why 32 is correct for struct a. The int j is 4 bytes, at a multiple of 4; since it comes immediately after struct a a1 it need no padding, being placed a multiple of 8. struct a a2 needs to be at a multiple of 8, so 4 bytes of padding are added. Overall, struct b needs 32 bytes for member a1, 4 bytes for member j, 4 bytes of padding (to bring a2 to a multiple of 8) and 32 for member a2 for a total of 72.

Upvotes: 1

Myst
Myst

Reputation: 19221

From my calculations, struct a requires 26 bytes (including padding in the middle) + 6 bytes at the end. It looks something like this:

struct a {
  float* f;  // takes 4 bytes
  char c;    // takes 1 bytes + 3 padding
  int I;     // takes 4 bytes
  char z[4]; // takes 4 bytes
  double d;  // takes 8 bytes, sets a requirement for memory alignment
  short s;  // takes 2 bytes.
  // here there are 6 more bytes for padding required for array alignment.
};

The double in the struct means that struct a must be positioned on an 8 byte alignment mark, so that the double is correctly aligned.

Now, when we have struct b, we have:

struct b {
   struct a a1; // takes 32 bytes, REQUIRES and 8 byte alignment
   int j; // takes 4 bytes + 4 byte padding (for alignment).
   struct a a2; // takes 32 bytes, MUST start on an 8 byte alignment
};

I hope this wasn't homework or something... :-p

Upvotes: 2

Related Questions