Relay-Version: version B 2.10 5/3/83; site utzoo.UUCP Posting-Version: version B 2.10.2 9/18/84; site dciem.UUCP Path: utzoo!dciem!msb From: msb@dciem.UUCP (Mark Brader) Newsgroups: net.lang.c Subject: Re: Block Initialization; structs and sizeof Message-ID: <1971@dciem.UUCP> Date: Fri, 10-Oct-86 13:56:44 EDT Article-I.D.: dciem.1971 Posted: Fri Oct 10 13:56:44 1986 Date-Received: Fri, 10-Oct-86 15:14:21 EDT References: <586@calma.UUCP> Reply-To: msb@dciem.UUCP (Mark Brader) Distribution: net Organization: NTT Systems Inc., c/o DCIEM, Toronto Lines: 38 Summary: Do scalar structs have a trailing padding? Suppose that, on your machine, ints are 4 bytes and must be aligned on multiples of 4 bytes. Chars, of course, are 1 byte. Now declare: struct str {int i; char c;} arr[2], sca; char buf[32]; Now, in arr, each i member must go on a new 4-byte boundary, so there is 3 bytes of padding after each c member. So sizeof arr[0] is 8. The most recent ANSI draft that I've examined specifies that if sizeof is applied to a structure type, the result is the size of such a structure including any trailing padding that would be necessary in an array of such structures. Therefore sizeof (struct str) is also 8 and, as far as I know, sizeof sca is also 8. However, the scalar struct sca is not required to have those 3 bytes of padding. This suggests that some compilers may place another variable, say buf, at ((char *) &sca) + 5. In this case a construct such as the "bzero(&p, sizeof(p))" mentioned in Sin-Yaw Wang's article The problem is that sca, the scalar struct, is NOT required to have those 3 bytes of padding*. Thus some compilers may decide to economize on storage and place another variable, say buf, 5 bytes past the start of sca. And then, of course, something like the "bzero(&sca,sizeof sca);" proposed in Sin-Yaw Wang's article (to which this is a followup) will overwrite the first 3 elements of buf! *K&R Appendix A does not speak of trailing padding at all; the most recent draft ANSI standard that I've examined does not speak of trailing padding in scalar structs. I mentioned this to Larry Rosler, but I have not been able to check a later draft. Of course, even if this is now covered, it doesn't affect current compilers. ARE there any compilers out that don't always put trailing padding on structs? (Note: replies of the form "my compiler does put padding" should not be posted unless there are a bunch of replies the other way!) Mark Brader, utzoo!dciem!msb #define MSB(type) (~(((unsigned type)-1)>>1))