TC bug in sizeof()?

John S. Price john at stat.tamu.edu
Fri Feb 16 10:21:53 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?

No, it's not a bug.  You've basically answered your own question, also.
The fact is, the word alignment makes thing WORD ALIGNED. That is, if you
define your structure

>struct test
>  { char a;
>    char b;
>    char c;
>  } structure;

with word alignment, the sizeof() this IS 4.  A word on a PC is 2 bytes, 
so all structures must fall on 2 byte boundries.  If this structure
was 3 bytes long, then then next object in memory would fall on
a byte boundry, which is wrong.  Think of this:

struct test array[10];

10 consecutive test structures in memory.  If they weren't 4 bytes long,
this array would not work, for you want word alignment.

<char a><char b><char c><char a><char b><char c>
 1 byte  1 byte  1 byte  1 byte  1 byte  1 byte
                        ^ this point right here is on a byte alignment,
                          which is against the word alignment.

In memory this structure would be, if you wanted word alignment:
<char a><char b><char c><one wasted byte><char a><char b><char c>

It's not a bug.

--------------------------------------------------------------------------
John Price                   |   It infuriates me to be wrong
john at stat.tamu.edu           |   when I know I'm right....
--------------------------------------------------------------------------



More information about the Comp.lang.c mailing list