Question

I was wondering, if structs are manually padded so each member is aligned at an address multiple of its size and all objects are of known explicit width, to what degree can I expect that the binary layout will be exactly the "expected"/intended one? Perhaps there are some compiler specific options to ensure that the layout will be exactly as declared?

IIRC the C standard does not allow any reordering, so only eventual extra padding is in question. Would the compiler need to add padding if the structure is padded according to its own alignment rules?

Was it helpful?

Solution

By default, compiler will align to 32 or 64bit. And yes, there are compiler specific options that set alignment to a custom value.

So if you want to control alignment of struct fields, you can do that either with compiler flags or with pragmas.

With GCC that would be -fpack-struct=[n]

In source code, you can surround the definition of your struct with #pagma pack or #pagma push(pack):

#pragma pack(push(n))
typedef struct my_struct {...} my_struct_t;
#pragma pack(pop)

GCC documentation: http://gcc.gnu.org/onlinedocs/gcc/Structure-Packing-Pragmas.html

MSDN documentation: http://msdn.microsoft.com/en-us/library/2e70t5y1.aspx

OTHER TIPS

You can specify in your code a forced padding via for example: __attribute__((aligned (16))); And I think there is another attribute name packed to specify that you don't want the compiler to align your structure. For more information, cf this link

(I could be wrong, but) I'm not aware of anything in the Standard that requires padding to be minimal. Given that, the compiler appears to be within its rights to put arbitrary amounts of padding between members and at the end of the structure (but not at the start), even if that padding isn't required to satisfy an alignment requirement. Manually padding to 32 or 64 bits isn't therefore guaranteed to prevent the compiler adding padding, even if it probably does for all practical compilers.

As others point out, there are compiler-specific (i.e. non-Standard) ways to force a struct to have no compiler-supplied padding at all, but not otherwise to control padding.

Even if you can specify the padding exactly, you still haven't defined the structure contents precisely because you haven't defined the representation of the members (e.g. big- or little-endian integers), so I'm not sure what you gain from this, particularly if portability is needed. You've defined member's offsets precisely, but not their representations.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top