TC bug in sizeof()?

David Doerschuk doerschu at rex.cs.tulane.edu
Sat Feb 17 04:00:09 AEST 1990


In article <1519 at maytag.waterloo.edu> dmurdoch at watstat.waterloo.edu (Duncan Murdoch) writes:
>
>A friend of mine has found something surprising in TC.  Neither of us knows
>C well enough to know for sure that this is a bug, but it looks like one.
>As illustrated in the program below, if a structure is an odd size, and
>is compiled with Word alignment, the sizeof function rounds the size up
>one byte.
>
>Is this a bug?
>
>Sample program:
>
>struct test
>  { char a;
>    char b;
>    char c;
>  } structure;
>
>main()
>{
>  printf("Size of structure= %d\n",sizeof(structure));
>}
>
>This prints a 3 if compiled with byte alignment, an 4 if compiled with word
>alignment.

Duncan, that's not a bug, its a feature! (sorry!)  No, seriously, your C
compiler is working correctly.  The story is this:  You get to choose
whether you want byte or word allignment.  The byte allignment stores
those three chars just as you'd expect, one right after the other, and
then the "next available" space for a second structure of three chars is
immediately after the first.  Word allignment also stores the 3 chars one
right after another, but then leaves a byte of "dead space" in order to
let the *next* structure start on a word boundary (a word, here, being
2 bytes).  The sizeof operation correctly reports (when using Word allign-
ment) that a total of 4 bytes are being "used" by the structure, even
though one of the bytes is dead space.  Use byte allignment if you've
got a lot of structures to store in memory and *need* that extra byte.
(note that the dead-space byte will appear every time you create one
of these structures, so if you've got 10,000 of them in memory, you've
got 10,000 dead-space bytes!)  Use word allignment if you've got
lots of memory, but need execution speed.  The whole idea of word
allignment is that the memory unit can fetch constructs beginning on
a word boundary faster than if they start between word boundaries.

Moral of the story:  Use sizeof() frequently, because things aren't
always what they seem! By the way, sizeof() costs you nothing at
execution time.  It is evaluated at compile time.

Good Luck!
Dave
doerschu at rex.cs.tulane.edu



More information about the Comp.lang.c mailing list