Path: utzoo!attcan!uunet!husc6!bloom-beacon!gatech!uflorida!novavax!proxftl!bill From: bill@proxftl.UUCP (T. William Wells) Newsgroups: comp.lang.c Subject: Re: sizeof( _variable_ ) Message-ID: <529@proxftl.UUCP> Date: 23 Jul 88 13:09:31 GMT References: <1264@bc-cis.UUCP> Reply-To: bill@proxftl.UUCP (T. William Wells) Distribution: na Organization: Proximity Technology, Ft. Lauderdale Lines: 44 Summary: Expires: Sender: Followup-To: Keywords: In article <1264@bc-cis.UUCP> john@bc-cis.UUCP (John L. Wynstra) writes: : : I recently ran up against this one, and, would like to toss it out to : NetLand. I had coded (on a 3b2 running System V.3) the following, : : typedef struct { : char x[10]; : char y; : char xx[10]; : char yy; : } Stuff; : : Stuff z; : : Later on in the same code I had a reference to sizeof(z) expecting to get 22 : (which is btw what I just now got on the bsd 4.2 vax), but what I got was 24! : : "Aha!" said I, "either character data is being aligned to even byte : boundaries [which, with an octal dump, I later proved to myself it wasn't] or : I've discovered a compiler bug". A colleague at work pointed out that, perhaps, : what I'm seeing is that storage is being allocated in units of 4 bytes, but : somehow that just doesn't seem right: I should think that sizeof( _variable_ ) : should be the length of the _variable_ not the length of the memory allocated : to it. Ah, well... : : So, can anyone out there enlighten me as to what is going on? What is happening is this: C defines the size of a type as if it were part of an array. Thus the size for Stuff is the size of whatever the size of an array element would be for an array of Stuff. Now, if it weren't for alignment, one could pack the array elements as close as one would like; however, for an array there may be padding to make the next element line up. A lot of compiler writers get lazy at this point. It seems that most of them want to make structure pointers all exactly equivalent. This means giving them the most restrictive alignment possible. In your case, there is no good reason why the structure must be aligned, so this is compiler-created waste. Note that this is not a compiler bug, any more than failing to write a good optimizer in the compiler is a bug. It is, however, very irritating.