sizeof on a word-oriented machine

Walter Murray walter at hpclwjm.HP.COM
Sat Nov 18 05:19:47 AEST 1989


Norman Diamond writes:

> Consider a machine where each 4-byte word has an address.
>   char x[37];
>   int  q;
>   q = sizeof x / sizeof (char);

O.K., but you still have to have a way of generating a pointer to
any particular element of an array.  And you are not allowed
to have &x[1]==&x[0].

> What is sizeof x?

37.

> If sizeof x is 40 (since 40 bytes are reserved for x) then the example
> on page 46 lines 12 to 13 (section 3.3.3.4) is violated.

You're right.

> If sizeof x is 37 then a user might do:
>   char *two_xs;
>   two_xs = malloc (2 * sizeof x);
> and get screwed because only 76 bytes will be allocated (2 * 37 rounded
> up to a multiple of 4) when 80 are really needed.

This could cause a problem only if the implementation isn't conforming
or the user makes assumptions not guaranteed by the dpANS.

> I think 40 is the most reasonable value for sizeof x.  Is the standard's
> example wrong?  May it be ignored?

I think the example is not wrong.  Consider the following.

   1.  The elements of an array must be allocated contiguously.
   2.  The sizeof operator yields the size (in bytes) of its operand.
   3.  sizeof(char)==1
   4.  Applied to an array, sizeof yields the total number of bytes
       in the array.

It seems to me the only conclusion is that the dpANS guarantees that
sizeof(x)==37.  Any unused bytes following the last element of an 
array are not counted in its size.

Walter Murray
--- 



More information about the Comp.std.c mailing list