www.delorie.com/archives/browse.cgi   search  
Mail Archives: djgpp/1996/04/14/15:03:22

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: <m2n34ijw64.fsf@presto.med.upenn.edu>
References: <Pine DOT A32 DOT 3 DOT 92 DOT 960406153743 DOT 75628A-100000 AT acs5 DOT acs DOT ucalgary DOT ca>
<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 <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 -


  webmaster     delorie software   privacy  
  Copyright © 2019   by DJ Delorie     Updated Jul 2019