TC bug in sizeof()?

Paul S. R. Chisholm psrc at pegasus.ATT.COM
Fri Feb 16 15:51:36 AEST 1990


< Krasny Oktyabr:  the hunt is on, March 2, 1990 >

In article <1519 at maytag.waterloo.edu>, dmurdoch at watstat.waterloo.edu (Duncan Murdoch) writes:
> 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.

struct mystruct /* changed from "struct test" in Duncan's code */
  { char a;
    char b;
    char c;
  } structure;

> This prints a 3 if compiled with byte alignment, a 4 if compiled with
> word alignment.

Okay, what does "sizeof" mean?  It doesn't just include the data
elements; it also includes any padding, in the middle, or at the end.
If you have an array of mystructs, the space between two elements
(e.g., ( ( (long) & array[ 1 ] ) - ( (long) & array[ 1 ] ) ), that is,
convert each address to a number and subtract) has to include any
padding.

If word alignment is specified, TC will make every mystruct start on a
word boundary.  It can only do that in an array by adding a byte of
padding.  There's no way TC can tell if a mystruct is a member of an
array or not, so it calls the size four.  (Frankly, I'm surprised it
didn't put a pad byte after *each* member, so each member is word
aligned; I'd expected the answer to be six!)

> Duncan Murdoch

Paul S. R. Chisholm, AT&T Bell Laboratories
att!pegasus!psrc, psrc at pegasus.att.com, AT&T Mail !psrchisholm
I'm not speaking for the company, I'm just speaking my mind.



More information about the Comp.lang.c mailing list