Xref: utzoo comp.sys.ibm.pc:44589 comp.lang.c:25997 Path: utzoo!utgpu!jarvis.csri.toronto.edu!cs.utexas.edu!samsung!uakari.primate.wisc.edu!uflorida!rex!doerschu From: doerschu@rex.cs.tulane.edu (David Doerschuk) Newsgroups: comp.sys.ibm.pc,comp.lang.c Subject: Re: TC bug in sizeof()? Message-ID: <2239@rex.cs.tulane.edu> Date: 16 Feb 90 17:00:09 GMT References: <1519@maytag.waterloo.edu> Reply-To: doerschu@rex.UUCP (David Doerschuk) Organization: Computer Science Dept., Tulane Univ., New Orleans, LA Lines: 52 Summary: Expires: Sender: Followup-To: Distribution: Keywords: In article <1519@maytag.waterloo.edu> dmurdoch@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@rex.cs.tulane.edu