Structure Member Padding

Scott David Daniels daniels at ogicse.ogc.edu
Tue Jul 10 03:25:41 AEST 1990


In article <13321 at smoke.BRL.MIL> gwyn at smoke.BRL.MIL (Doug Gwyn) writes:

In article <13321 at smoke.BRL.MIL> you write:
>...
>Your argument about struct member alignment seems correct, but it raises
>a problem with
>	struct {
>		short s;
>		char a, b, c;
>	};
>on a word-addressed architecture, if short is made a half-word.  Note that
>your line of argument would lead to the conclusion that there can be no
>padding before the first char, but in such a situation a half-word of
>padding would be necessary.  So, if your interpretation is correct, an
>implementor in such an environment would have to make his shorts full-
>word sized.  This may not be a big problem, but I'm somewhat surprised
>by this.  I think we could use an official interpretation ruling here too.

You may be more convinced when you realize that

	struct { short s; char a; };
	struct { short s; char a, b; };
	struct { short s; char a, b, c; };

should all have the same head (that is, the addition of b and c should not
move where a belongs).  The reason for wanting this is obvious: people often
build variant records in C by sharing heads, then including enough information
in the head to distinguish which tail is used.  Unfortunately, I believe the
standard goes a bit too far in specifying layout by insisting on an order for
the layout that precludes packing the record.

	struct first { char a; short s; };

	struct second{ char a; short s; char b; };

	struct third { char a; char b; short s; };

The first will be layed out (on a machine with alignment requirements):
	<a> <waste> <s>
I believe the second must therefore be layed out:
	<a> <waste> <s> <b> <possible waste> 
The third may be layed out:
	<a>   <b>   <s>

I would like to be able to use the same layout for third and second, thus
making packed data structures (while still keeping the alignment efficiency).
This can easily be done by the compiler (it simply keeps track of holes and
their alignments, and fills them whenever an appropriate (non-array) element
is added.  The reason for non-array is to allow the existing code that extends
a struct by adding to a final array at the end to continue to work.  However, 
I believe the standard requires me to use the layout that I have shown.  Am 
I wrong?  Can someone explain why this specification of the the layout is 
actually useful or desireable? ...

-Scott David Daniels
daniels at cse.ogi.edu			Just another puzzled programmer.



More information about the Comp.std.c mailing list