Can the struct padding be safely used by the user

2019-06-20 04:49发布

问题:

Assuming I have a struct like the following:

struct Struct {
    char Char;
    int Int;
};

and sizeof( int ) is greater than one and the compiler adds padding for the Char member variable - is the compiler-generated code allowed to change the values of the padding bytes?

I mean if I use pointer arithmetic and write some data into the padding bytes surrounding the Char member variable and later do variable.Char = assignment is it possible that the code generated by the compiler will also overwrite some of the padding bytes?

回答1:

The following sentence is wrong: No, it would not overwrite the padding bytes. But it probably is not a good practice to use that. If you need it, add member variables there.

I researched based on comments indicating (correctly) that I am stupid:

The C Standard has an "Annex J" with section J.1 Unspecified behavior. It says, "The value of padding bytes when storing values in structures or unions". The implication is that the compiler can generate whatever instructions it wants to write the data into the structure, which may allow it to overwrite padding after a member.



回答2:

What if the compiler were smart enough to use a word write to save the char? Your carefully saved data would be lost. ;-)



回答3:

You sure can write something there, and memset-ing an instance of such structure does that. However, it's not safe and never a good idea to do so. Some other day another developer puts a #pragma somewhere or adds a member to struct declaration and your code will explode in many weird and fancy ways, which could take quite a while to debug.



回答4:

The only reason to do this would be something like a plugin evilly tricking a host application into storing extra data.

Don't do it though, because at some point in the future it will break, and it will be a severe headache for all concerned.