Is it possible to safely use a structure add-in using user code?

Assuming I have a structure like:

struct Struct { char Char; int Int; }; 

and sizeof( int ) more than one, and the compiler adds an addition for the Char member variable - is this the code generated by the compiler that allows you to change the values ​​of padding bytes?

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

+6
c ++ c struct alignment padding
source share
4 answers

The following sentence is false : No, it will not overwrite pad bytes. But probably this is not a good practice. If you need it, add member variables there.

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

Standard C has β€œAppendix J” with section J.1 Unshown behavior . It says: "The value of padding bytes when storing values ​​in structures or associations." The implication is that the compiler can generate any instructions that it wants to write to the structure, which can allow it to overwrite the filling after the member.

+10
source share

What if the compiler is smart enough to use the word write to save char? Your saved data will be lost .; -)

+13
source share

You can write something there, and memset insert an instance of such a structure. However, it is not safe and is never recommended . The next day, another developer puts #pragma somewhere or adds a member to the structure declaration, and your code will explode in many strange and bizarre ways, which can take quite a while to debug.

+4
source share

The only reason for this is something like a plugin that is maliciously tricking the host application into storing extra data.

Do not do this, because at some point in the future it will break, and this will be a serious headache for everyone concerned.

+1
source share

All Articles