0

Am trying to understanding the struct padding. The below struct is padded:

struct s {
int j;
char c;
int i;
};

==> sizeof(struct s) = 12

But for this struct it is not padding. why?

struct s {
char c;
}

==> sizeof(struct s) = 1 OR

struct s {
short int i;
}

==> sizeof(struct s) = 2

Why the padding is not applicable for the above two structs?

Jayesh Bhoi
  • 24,694
  • 15
  • 58
  • 73
kee
  • 46
  • 2
  • 10
  • 4
    Padding is traditionally done to put members on offsets that are good from a CPU perspective. If you only have a single member, the offset is always going to be zero, no need for padding. – Some programmer dude Sep 22 '14 at 09:06
  • You can check [this answer](http://stackoverflow.com/questions/12861582/why-is-padding-added-for-multiple-data-members-of-structures-and-not-for-single) – Jayesh Bhoi Sep 22 '14 at 09:10

2 Answers2

1

Padding is done to keep members of the struct aligned, so that access is fast.(*) Consider what happens in an array of structs:

struct s {
    int i;
    char c;
};

struct s a[0];

If this struct were not padded, a[1] would have the address (char *)a + 5. That's unaligned, assuming a[0] is aligned. Therefore, the struct will typically be padded to a multiple of sizeof(int). (Were i a long long, then the whole struct would be padded to a multiple of sizeof(long long); try and see.)

With a single char, there's no need to pad because the char will be aligned anyway, while there are no other members that become unaligned. With a single short, an alignment of 2 is sufficient to keep the single member aligned, always.

(*) On some CPUs, but not Intel x86-compatible ones, unaligned access can actually crash your program.

Fred Foo
  • 355,277
  • 75
  • 744
  • 836
0

The padding is added to make sure that the int member i is aligned.

Assuming that your int is 4 bytes in size, then it will be placed on a 4 byte boundary to align it. That means that there are 3 bytes of padding after the char. The size of 12 is therefore quite reasonable.

Imagine if there was no padding. Then the offsets would be:

Member  Offset
j       0
c       4
i       5

If the struct was laid out this way then i would be mis-aligned. To place it on a 4 byte boundary, it needs to be at offset 8. Hence the 3 bytes of padding, and the total size of 12. So, the actual layout is:

Member    Offset
j         0
c         4
<padding> 5
i         8
David Heffernan
  • 601,492
  • 42
  • 1,072
  • 1,490