Path: utzoo!utgpu!news-server.csri.toronto.edu!clyde.concordia.ca!uunet!wuarchive!zaphod.mps.ohio-state.edu!ncar!gatech!prism!sun13!sun10.scri.fsu.edu!mayne From: mayne@sun10.scri.fsu.edu (William (Bill) Mayne) Newsgroups: comp.lang.c Subject: sizeof(struct) and padding Message-ID: <1229@sun13.scri.fsu.edu> Date: 19 Oct 90 18:46:14 GMT Sender: news@sun13.scri.fsu.edu Organization: SCRI, Florida State University Lines: 30 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@nu.cs.fsu.edu