0

Take the following struct:

struct s {
  char c; // 1 byte
  long l; // 8 bytes
};

C would add 7 bytes of padding between c and l, making the size of the struct 16 and the alignment of the struct 8. If I told the compiler to pack the struct, how is the alignment evaluated? Does it just give up and make the alignment 1 byte?

EDIT:

This question is not a duplicate of Struct Padding and Packing. I am asking how the alignment of a packed struct is evaluated. Not how padding is done or how the alignment of a regular struct is evaluated. If the above struct is padded, it has a size of 16 and an alignment of 8--the alignment of its largest member (the long). If it is packed, it has a size of 9 bytes and an alignment of ? bytes.

Sam Claus
  • 1,807
  • 23
  • 39
  • Wouldn't a quick test using sizeof() answer this? – Ken White Dec 23 '17 at 06:22
  • @KenWhite No, it would not. Not a very complicated question. I am trying to understand the alignment of the packed struct, not the size. – Sam Claus Dec 23 '17 at 06:36
  • @KenWhite Maybe I'm wrong. As far as I've been told, `sizeof` would just return `9`, and total size of a struct has nothing to do with its alignment. Correct me if I'm wrong. – Sam Claus Dec 23 '17 at 06:39
  • If sizeof() returns a value that isn't a power of 2, there isn't any alignment, is there? Is 9 a power of 2? What would an alignment boundary be for 9? – Ken White Dec 23 '17 at 06:41
  • Okay yes that applies for this struct. But let's say we have a struct with an `int` and a `long`, and it's packed. It's size is now 12 bytes rather than the usual 16 with packing. Would this be aligned on a 2 or 4 byte boundary, vice versa? – Sam Claus Dec 23 '17 at 06:45
  • Is 12 a power of 2? – Ken White Dec 23 '17 at 06:47
  • No it isn't. Sorry for my temper, I'm clearly not understanding alignment properly in the first place. Was getting frustrating not being able to find what seemed like a simple answer when I'm missing some key knowledge. Are you trying to say that if the size isn't a power of 2 it will just be placed at any address (alignment of 1)? – Sam Claus Dec 23 '17 at 06:54

0 Answers0