Xref: news2.mv.net comp.os.msdos.djgpp:2694 From: jes AT presto DOT med DOT upenn DOT edu (Joe Smith) Newsgroups: comp.os.msdos.djgpp Subject: Re: SIZEOF disparity...? Date: 11 Apr 1996 17:19:31 -0400 Organization: University of Pennsylvania Lines: 49 Sender: jes AT presto DOT med DOT upenn DOT edu Message-ID: References: <4khbdr$1on AT vidar DOT diku DOT dk> NNTP-Posting-Host: presto.med.upenn.edu In-reply-to: terra@diku.dk's message of 10 Apr 1996 22:06:51 GMT To: djgpp AT delorie DOT com DJ-Gateway: from newsgroup comp.os.msdos.djgpp In article <4khbdr$1on AT vidar DOT diku DOT dk> terra AT diku DOT dk (Morten Welinder) writes: > Mike writes: > > >typedef struct > >{ > > char magic[2]; > > long size; > > int dummy; > > long offset; > >} header_t; > > >it returns 16, when it should return 14 (2 chars = 2 + long (4) + int (4) > >+ lont (4) = 2+4+4+4=14) > > This argument is incorrect. The size of the struct should be > > 2 + P1 + 4 + P2 + 4 + P3 + 4 + P4 > > where P1,...,P4 are arbitrary non-negative integers. (This, of > course, assuming that longs and ints are fours bytes each.) > ... Maybe this is obvious to everybody else, but I got burned the other day by assuming that only the structure elements were padded, when, in fact, the size of the whole structure is also considered (I think this would be P4 in Morten's scheme). Like everyone else, I wanted to use a structure as a file header, but I knew gcc was going to try to align the members. Trying to be smart (and trying to avoid explicitly packing the elements), I placed the long element first, assuming it wouldn't need extra padding. Gcc outsmarted me though, and padded the size of the structure to a multiple of four; I suppose to preserve alignment if it were used in an array (which it wasn't). So, read(fd, buf, sizeof(struct header_t)) was reading two bytes too far even though none of the structure elements needed padding. Sigh. Structures as file headers: just say 'no'.