Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is the amount of padding in structure in C is Compiler dependent or well defined?

Tags:

c

padding

Is the a amount of padding in C struct well defined in standards or compiler and/or target architecture dependent. I could not find an answer in the standards.

like image 252
phoxis Avatar asked Feb 20 '23 16:02

phoxis


2 Answers

It is implementation-defined. From section 6.7.2.1 of the C99 standard:

...Each non-bit-field member of a structure or union object is aligned in an implementation-defined manner appropriate to its type...

...There may be unnamed padding within a structure object, but not at its beginning...

The compiler will typically choose an arrangement that suits the underlying hardware (aligning things to be easy to read from memory, etc.).

like image 177
Oliver Charlesworth Avatar answered Apr 28 '23 03:04

Oliver Charlesworth


Padding is determined by the implementation, by which we mean the specific compiler that you use to compile the code.

On certain platforms there are agreed conventions as to what padding will be used. This is what makes binary interop possible for code compiled by different compilers.

So, whilst in theory different compilers can make different choices, so long as all the code is running inside a single process, different padding rules are seldom an issue. On the other hand, if you decide to use struct layouts for data that you send over a network, then you will invariably run into problems. Don't use the binary layout structs for data that goes on the wire.

like image 45
David Heffernan Avatar answered Apr 28 '23 05:04

David Heffernan