TC bug in sizeof()?

Martin Weitzel martin at mwtech.UUCP
Wed Feb 28 21:46:46 AEST 1990


In article <25E9856C.8135 at maccs.dcss.mcmaster.ca> cs4g6ag at maccs.dcss.mcmaster.ca (Stephen M. Dunn) writes:
|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?
|
|   Well, it depends on how you define "bug" ... I don'
|t have a copy of
|K&R to check exactly what they say about it, but according to their
|definition it may be.  However, it does make sense, since when compiled
|with word alignment that extra byte is not available for anything
|else and is allocated along with the structure.  Since it's reflecting
|the way things really work, you could say it's the most accurate way
|of doing it.
|-- 
|Stephen M. Dunn                               cs4g6ag at maccs.dcss.mcmaster.ca
|          <std_disclaimer.h> = "\nI'm only an undergraduate!!!\n";
|****************************************************************************
|               I Think I'm Going Bald - Caress of Steel, Rush

It's common practice to write the following piece of code:

	struc { ....... } x[100];
	int i;

	for (i = 0; i < sizeof x / sizeof x[0]; i++)
		/* do something with x[i] */

To make this work, it must allways be guaranteed for any array,
that you can compute the number of elements by dividing the total
size thrue the size of one element.

BTW: In many of my programs I find the following very handy:

	#define elementsof(z) (sizeof z / sizeof z[0])

which makes the above a little more readable, as you could write:

	for (i = 0; i < elementsof(x); i++)

GENERAL RULE:
	The 'sizeof' every object is the number of bytes,
	this object would occupy as array element.

A not so obvious further aspect is, that a struct must begin on a
boundery, that has the same alignment as the struct-s component
with the most restrictive alignment. If it were not, you would end
up with elements of different size, if you build an array of such
struct-s. (Think a little about this, if you don't believe it.)
-- 
Martin Weitzel, email: martin at mwtech.UUCP, voice: 49-(0)6151-6 56 83



More information about the Comp.lang.c mailing list