C structs & A question about octet
Guy Harris
guy at sun.uucp
Thu Nov 6 05:29:14 AEST 1986
> I have a question about alignment and padding. I have noticed (context:
> Vax 780, 4.3BSD) that the c compiler pads out struct sizes to be
> long word aligned.
Well, no, actually, it doesn't. It *aligns* members of structures on the
same boundaries that it would align non-structure-member items of the same
type. Thus, in your example, the "short" would be aligned on a 2-byte
boundary; since the only thing that precedes it is a single "char", it would
require one padding byte between them.
On some machines, it simply doesn't have much of a choice. It *could*,
presumably, just pack the structure as tightly as possible; however, it
would then have to generate a *lot* of extra code to access members not on
their "proper" boundary. (No, Virginia, not all machines allow
arbitrary-boundary references to "short"s, "int"s, "long"s, etc..)
On other machines, it could pack the structure as tightly as possible,
because those machines do allow arbitrary-boundary references to "short"s,
"int"s, etc.. It would just mean the code would run more slowly, since few
(if any) machines that allow arbitrary-boundary references do them as
quickly as proper-boundary references.
> For all of you that knew this, you're all saying big deal, so what? Well,
> I do (did) stuff like this all the time:
>
> head = (three_bytes*)calloc(N, sizeof(three_bytes));
>
> This wastes N bytes. Sometimes N is around 10 to the 7th or 8th. Bad news.
> The fact that pointer arith is "wrong" makes this very icky to work around
> even if you are aware of the problem. Anyone have any comments or
> suggestions? Does everyone except me know about this?
Allocating arrays that big is relatively uncommon; C's padding rules make
the more common cases work well, and as such are doing the right thing. I'd
suggest you allocate 3*N bytes as a single array, and then extract the
"short" yourself. NOTE: if you absolutely insist on doing this extraction
by casting a pointer to the byte following the "char" into a "short *", and
just dereferencing that pointer, surround that code with some "#ifdef" and
put a more portable version in the "#else" clause!
--
Guy Harris
{ihnp4, decvax, seismo, decwrl, ...}!sun!guy
guy at sun.com (or guy at sun.arpa)
More information about the Comp.lang.c
mailing list