Search code examples
calignment

sizeof vs _Alignof value


Is there ever a time when the _Alignof returns a different value that sizeof? For example, every one that I've tried yields the same value:

printf("%zu %zu\n", _Alignof(int), sizeof (int));
printf("%zu %zu\n", _Alignof(char), sizeof (char));

4 4
1 1

Are these two values ever different (other than with an array)?


Solution

  • For struct foo { int i; char c};, many C implementations produce eight for sizeof(struct foo) and four for _Alignof(struct foo) because int is four bytes big and has an alignment requirement of four bytes. This is because the structure must have four-byte alignment to satisfy the int alignment, and that requires adding three bytes of padding, so the structure size is four bytes for the int, one for the char, and three for the padding.

    Another possibility is that long double is 16 bytes in size but only requires eight-byte alignment. It might be 16 bytes because that much data is needed for it, but the hardware might have only an eight-byte bus, so only eight-byte alignment is required to be able to efficiently load the parts of any object.

    Similarly, any machine will generally have some strictest alignment require x bytes because its bus is x bytes wide or its processor has a largest general word size of x, so the hardware can only process things in chunks of x bytes at a time. Then any objects larger than x bytes must be made out of multiple words and implemented using multiple instructions. For such objects, there is no need for alignment stricter than x bytes. For example, an eight-byte integer might be made out of two four-byte words with four-byte alignment, or, on older machines, a four-byte integer might be made out of two-byte words with two-byte alignment.