Block Initialization; structs and sizeof
Mark Brader
msb at dciem.UUCP
Sat Oct 11 03:56:44 AEST 1986
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))
More information about the Comp.lang.c
mailing list