Is the compiler allowed to clobber struct padding?

Continuing the discussion from Padding struct to fixed size with usable bytes:

Something has just occured to me.
In the solution I’ve accepted the struct padding is accessed via pointer casting, so basically without the compiler ‘knowing’ about my intention to use the padding bytes to store information.

Is the compiler allowed to clobber the padding of a struct? Could it, for example, use a 64 bit atomic for state because it’s faster on some system or whatever and just overwrite the 4 padding bytes after state on every write to it?

The C standard states:

J.1 Unspecified behavior
The following are unspecified:
[…]
— The value of padding bytes when storing values in structures or unions (6.2.6.1).
[…]

Is this also true for Zig? If it is what does this mean exactly and how could I solve this problem?

1 Like

Not sure there’s a solid answer here, but the LLVM back-end easily might.

What won’t get clobbered: a [N]u8 array of the size the padding would be. This is probably a good idea here.

2 Likes

Yes it is allowed and in fact is already done for example for storing type safety information. If you want to reserve space within struct padding, simply declare the data as a field along with the others.

4 Likes

Thanks for the clarification this makes total sense!
I’ve actually come up with a (admittedly a little ridiculous) solution for finding the exact size the padding needs to be here. Maybe I should just admit defeat and use extern containers for things like this…