Subject: Re: Use of sizeof()
To: Robert Black <>
From: Danny Thomas <>
List: current-users
Date: 07/11/1995 21:51:30
>This takes the form of assuming that structs are only aligned to the
>alignment of their largest data type.
>For example with a structure like
>typedef struct
>        short a;
>        short b;
>        short c;
>} foo;
>it is assumed that sizeof(foo) == 6. Some compilers (notably gcc/arm)
>will give a value of 8 because all structs are word aligned regardless
>of contents so sizeof() returns the amount of space required to store a
>struct in an array.
>Which is broken: the NetBSD code or the compiler?

the code

the important point thing to remember is assumptions about structure
padding or lack thereof are just that, assumptions, and are inherently
non-portable and non-ANSI code. Some compilers will change alignment
depending on options such as switches for packed alignment or the CPU model
being compiled for. About the only thing ANSI C guarantees is that
structure members are placed in memory in the order they were declared in
the structure definition. Hence the inclusion of offsetof().

while I think the ANSI standard (with rationale) is one of the better
standards at least the few times I've looked at it, Harbison & Steele is
the first place to look for an answer, in this case 4th ed p139

>The size of a structure type is the amount of storage necessary to
>represent all components of that type, including any unused padding
>space between or after the components. The rule is that the structure
>will be padded out to the size the type would occupy as an element
>of an array of such types. (For any type T, including structures,
>the size of an n-element array of T is the same as the size of
>T times n.) Another way of saying this is that the structure must
>terminate on the same alignment boundary on which it started -
>that is, if the structure must begin on an even byte boundary,
>it must also end on an even byte boundary. The alignment requirement
>for a structure type will be at least as stringent as for the
>component having the most stringent requirements.

the relevant part as far as the original question is "will be at LEAST as
stringent", in the last sentence above. GCC satisfies this but is "not
precisely as stringent as".

perhaps this was the problem in the SCSI subsystem recently alluded to?

Danny Thomas  (