sizeof(struct) and padding

William Bill Mayne mayne at sun10.scri.fsu.edu
Sat Oct 20 04:46:14 AEST 1990


Some time ago the issue of the value of sizeof(S) where S is
a structure requiring alignment came up in this news group.
It turns out that sizeof(S) will include not only all the
content of S. It also counts any padding necessary to ensure
the allignment of another S, even if S is not declared as
part of an array. This is good if your usage is:

   s_array = malloc(n*sizeof(S)); /* Where s_array is a pointer
                                     to type S */

But in other cases it is not so good. If sizeof() is being used
to get the number of bytes for memcpy() the padding bytes will
be copied unnecessarily. If space is being allocated for a single
structure extra memory may be allocated, but this probably won't
make any difference since the space for the padding would usually
be wasted anyway. 

"Big deal!" you say? Actually it could make an important differnce
if the structure is being written as a record to a file. Then  extra 
file space will be used. Unless I intend to read or write arrays of
records some of the time, changing the number of records handled, 
with each operation, this is a real waste.

The $64K question is: How do I portably get the actual size of
a structure without padding when I need that rather than
what sizeof() tells me? I have some methods that will work,
but I am not sure how portable they'd be and I hope someone
has a better way.

Bill Mayne     mayne at nu.cs.fsu.edu



More information about the Comp.lang.c mailing list