Mail Archives: djgpp/1996/04/14/15:03:22
In article <4khbdr$1on AT vidar DOT diku DOT dk> terra AT diku DOT dk (Morten Welinder) writes:
> Mike <mbwarren AT acs DOT ucalgary DOT ca> 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'.
<Joe
--
Joe Smith
University of Pennsylvania jes AT presto DOT med DOT upenn DOT edu
Department of Physiology
Philadelphia, PA 19104
- Raw text -