Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can the struct padding be safely used by the user code?

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?

like image 359
sharptooth Avatar asked Jan 06 '10 13:01

sharptooth


2 Answers

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

like image 76
Richard Pennington Avatar answered Oct 19 '22 23:10

Richard Pennington


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.

like image 10
Mark Wilkins Avatar answered Oct 20 '22 00:10

Mark Wilkins