sizeof(struct) and padding

Steve Summit scs at adam.mit.edu
Sat Oct 20 10:32:22 AEST 1990


In article <1229 at sun13.scri.fsu.edu> mayne at sun10.scri.fsu.edu (William (Bill) Mayne) writes:
[sizeof() reflects padding at ends of structures.]
>"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.
>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?

My $64,000 question is: why are so many poor souls condemned to
try to read and write binary data files?  Yes, it is easy and
quick to use fwrite and sizeof to write whole structs to a file,
but those are the only two good things which can be said about it.
Binary files are otherwise quite difficult to work with, not to
mention unportable, sometimes even to the same machine on which
they were written.  More flexible (e.g. text) file formats offer
hosts of advantages, and can be implemented reasonably easily and
efficiently as well.  (This debate appears here endlessly, and I
should add it to the FAQ if I could think of a succinct way.  I
won't repeat all the pros and cons right now.)

If a binary format has not already been forced upon you by some
prior decision or external piece of software (which it sounds
like it has not, since you are trying to figure out how to change
the format by eliminating the padding you feel is spurious) you
should strongly consider dropping binary formats entirely, and
moving to a simple text format.  I'd describe good ways to do so,
but I recently discovered that everything I'd say about data
files has already been published, in Jon Bently's book
Programming Pearls (or perhaps the sequel, More Programming
Pearls).

If you must compute the size of a structure less any trailing
padding, one way to do so would be

	struct x x;
	offsetof(struct x, last_member) + sizeof(x.last_member)

offsetof is a (relatively) new macro, standardized by ANSI, and
#defined in <stddef.h>.

(By the way, it is generally agreed that the advantages of having
sizeof account for trailing padding far outweigh any disadvantages.
Yet this issue apparently belongs in the FAQ as well.)

                                            Steve Summit
                                            scs at adam.mit.edu



More information about the Comp.lang.c mailing list