Structure Member Padding

Mark Brader msb at sq.sq.com
Sun Jul 8 08:51:41 AEST 1990


> > Does ANSI C enforce any inter-member "padding" standard?? 

> No.  ANSI C explicitly leaves this up to the implementation.
> That's pretty well the only viable approach ...

Well, here is what 3.5.2.1 actually says.  (Um, actually, this is from
the October 1988 draft.)

#  Within a structure object, the non-bit-field members and the units
#  in which bit-fields reside have addresses that increase in the order
#  in which they are declared.  A pointer to a structure object, suitably
#  converted, points to its initial member (or if that member is a bit-
#  field, then to the object in which it resides), and vice versa.
#  There may therefore be unnamed holes within a structure object,
#  but not at its beginning, AS NECESSARY TO ACHIEVE THE APPROPRIATE
#  ALIGNMENT.
#
#  ... There may also be unnamed padding at the end of a structure,
#  AS NECESSARY TO ACHIEVE THE APPROPRIATE ALIGNMENT were the structure
#  or union to be an element of an array.

Notice the emphasis that I have added: alignment is the only reason that
permits the use of holes or other padding.  Now, "alignment" is defined
in 1.6 as

#  a requirement that objects of a particular type be located on storage
#  boundaries with addresses that are particular multiples of a byte address.
(presumably meaning "with byte addresses that are multiples of a particular
value", but never mind, the intent is clear).

Note that alignment is a function of the type only, and it isn't
permitted for a type to have an alignment requirement larger than its
own size -- e.g., chars couldn't be required to be on even addresses --
because elements of an array are guaranteed to be adjacent (in 3.1.2.5).

It therefore appears to me that we can deduce that, in a struct such as

	struct {
		int	yksi;
		int	kaksi;
		char	kolme;
		char	nelja;
		char	viisi;
		int	kuusi;
		int	seitseman;
	};

the *only* places there could be padding are [1] after viisi, but
fewer than sizeof(int) bytes, and [2] at the end.  The consecutive
members of the same type have the same alignment requirement, and char
is guaranteed to have the least strict alignment requirement (in 3.3.4).

The overall struct type could have a stricter alignment requirement
than any member, so there could be padding at the end.

(Responses to this posting will probably not be read by me for 4 weeks.)

-- 
Mark Brader		"Europe contains a great many cathedrals, which were
Toronto			 caused by the Middle Ages, which means they are very
utzoo!sq!msb		 old, so you have to take color slide photographs
msb at sq.com		 of them."			-- Dave Barry

This article is in the public domain.



More information about the Comp.std.c mailing list