3

Can I guarantee that the size of any data structure is dividable by size of int because of data alignment? I didn't find information about how to guess the size of the data structure before compiling.

moamen
  • 169
  • 1
  • 7
  • Related: https://stackoverflow.com/questions/10309089/why-does-size-of-the-struct-need-to-be-a-multiple-of-the-largest-alignment-of-an – jarmod Sep 26 '20 at 13:26
  • 1
    Re “information about how to guess the size of the data structure before compiling”: C implementations are required to document the sizes and alignment requirements of their types, so seek that information in the compiler documentation. Then normal C implementations lay out their structures as given by [this algorithm](https://stackoverflow.com/a/11906915/298225). Only if there were some special purpose to be served would additional padding be inserted. – Eric Postpischil Sep 26 '20 at 13:31

1 Answers1

4

In general you cannot make this assumption:

  • If sizeof(int) == 1, all structures have a size that is a multiple of sizeof(int). This is the case on a few DSP chips.

  • Otherwise, on the vast majority of architectures, the sizes can be arbitrary and for example the size of struct A { char c; } may be 1, which is not a multiple of sizeof(int).

  • If the structure does have an int member that is not a bit-field, and is not explicitly or implicitly declared as packed with a compiler specific extension, you can assume that its size is a multiple of _Alignof(int) and has itself an alignment at least as large as _Alignof(int). This is true for any member type (except bit-fields). Note that it does not necessarily make the size a multiple of sizeof(int).

  • See how struct alignment is usually determined in this answer by Eric Postpischil.

  • See also why does size of the struct need to be a multiple of the largest alignment of any struct member.

chqrlie
  • 131,814
  • 10
  • 121
  • 189
  • 1
    @moamen: the text in the link, *data are always aligned as 4 bytes package which leads to insert empty addresses between other member’s address* is not precise enough. Padding may be inserted between some structure members or at the end of the structure to allow for proper alignment of all members, but my `struct A` has no such requirement. On most architectures its size will be `1`. Whether `sizeof(struct A)` may be larger than `1` on a conforming implementation is a separate question. – chqrlie Sep 26 '20 at 13:35