size of struct in C

CStructStructure Packing

C Problem Overview


> Possible Duplicate:
> Why isn’t sizeof for a struct equal to the sum of sizeof of each member?

Consider the following C code:

#include <stdio.h>    

struct employee
{
  int id;
  char name[30];  
};

int main()
{
  struct employee e1;      
  printf("%d %d %d", sizeof(e1.id), sizeof(e1.name), sizeof(e1));
  return(0);
}

The output is:

4 30 36

Why is the size of the structure not equal to the sum of the sizes of its individual component variables?

C Solutions


Solution 1 - C

The compiler may add padding for alignment requirements. Note that this applies not only to padding between the fields of a struct, but also may apply to the end of the struct (so that arrays of the structure type will have each element properly aligned).

For example:

struct foo_t {
    int x;
    char c;
};

Even though the c field doesn't need padding, the struct will generally have a sizeof(struct foo_t) == 8 (on a 32-bit system - rather a system with a 32-bit int type) because there will need to be 3 bytes of padding after the c field.

Note that the padding might not be required by the system (like x86 or Cortex M3) but compilers might still add it for performance reasons.

Solution 2 - C

As mentioned, the C compiler will add padding for alignment requirements. These requirements often have to do with the memory subsystem. Some types of computers can only access memory lined up to some 'nice' value, like 4 bytes. This is often the same as the word length. Thus, the C compiler may align fields in your structure to this value to make them easier to access (e.g., 4 byte values should be 4 byte aligned) Further, it may pad the bottom of the structure to line up data which follows the structure. I believe there are other reasons as well. More info can be found at this wikipedia page.

Solution 3 - C

Your default alignment is probably 4 bytes. Either the 30 byte element got 32, or the structure as a whole was rounded up to the next 4 byte interval.

Solution 4 - C

Aligning to 6 bytes is not weird, because it is aligning to addresses multiple to 4.

So basically you have 34 bytes in your structure and the next structure should be placed on the address, that is multiple to 4. The closest value after 34 is 36. And this padding area counts into the size of the structure.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser191776View Question on Stackoverflow
Solution 1 - CMichael BurrView Answer on Stackoverflow
Solution 2 - CDaniel BrotherstonView Answer on Stackoverflow
Solution 3 - CLiz AlbinView Answer on Stackoverflow
Solution 4 - CavpView Answer on Stackoverflow