sizeof c struct with char fields only

148 Views Asked by At

I understand how padding works. I know what the alignment is. What is strange for me is, why the size of the struct with char fields only is not aligned to 4 bytes (padding at the end)? I suspect this is simply not guaranteed by the specification, so compiler does not do that. If that's the case, can I get the reference to such rule? I'm mostly interested in x86 and x86-64 architectures.

Example:

struct foo {
    char field1;
    char field2;
    char field3;
} foo2;

int main(void)
{
    printf("sizeof=%lu\n", sizeof foo2);
}

output: sizeof=3

1

There are 1 best solutions below

4
On BEST ANSWER

The alignment of a structure must be such that all its fields are also aligned correctly (especially if they're part of an array).

Since all the fields here have an alignment requirement of one, that's also the alignment requirement of the structure itself.

In other words, if you put two of these structures next to each other, no field in either structure would violate the alignment requirement.

Contrast that with:

struct moreComplexCase {
    char char1WithAlignment1;
    // 3 byte gap to align below item.
    unint32_t uintWithAlignment4;
    char char2WithAlignment1;
    // 3 byte gap to align structure itself.
}

You'll see the two padding sections there. The first is to ensure the uint32_t is properly aligned (you should also be able to see that the structure alignment needs to be four as well so that the uint32_t aligns correctly with the given padding).

The final padding is to ensure a second element of an array (and, for that matter, all subsequent elements) will also be aligned correctly.

The C standard itself doesn't dictate what the alignment is, just that alignment may exist. For example, early x86 chips (and possibly the current ones) handle misaligned data just fine (or may do it a little slower) while other architectures (e.g., early ARM chips) will simply crash or raise a fault if you try to do that.