delorie.com/archives/browse.cgi   search  
Mail Archives: djgpp/1997/06/18/13:35:01

From: Shawn Hargreaves <Shawn AT talula DOT demon DOT co DOT uk>
Newsgroups: comp.os.msdos.djgpp
Subject: Re: The size of structures and binary files
Date: Fri, 13 Jun 1997 20:31:20 +0100
Organization: None
Distribution: world
Message-ID: <TPn3XOAIAaozEwXY@talula.demon.co.uk>
References: <33A1B030 DOT 309E AT post DOT psychologie DOT uni-bielefeld DOT de>
NNTP-Posting-Host: talula.demon.co.uk
MIME-Version: 1.0
Lines: 37
To: djgpp AT delorie DOT com
DJ-Gateway: from newsgroup comp.os.msdos.djgpp

>I have two structs:
>struct s1 { char c1; char c2; short s};
>struct s2 { char c1; short s; char c2};
>
>A call to sizeof will return 4 for s1 and 6 (!) for s2.
>It seems like the size of the chars in s2 gets increased to 2.

That's the result of structure padding: all (or at least all decent :-)
C compilers do this to make your programs work better. If the c1 in
structure 2 was allocated as a single byte, the short would be aligned
on an odd memory address, which on the intel means every reference to
that data would take twice as long (on other processors like the 68000
it would actually crash your program). Likewise the end of the structure
needs to be padded to an even address, so that you can create an array
of them without every other object being at an odd address...

>Now I wouldn't care much, if it weren't for writing and reading these
>structs to binary files.

If you really need to prevent the thing from being padded, put
__attribute__ ((packed)) after each field in your structure. See the
info docs about gcc C extensions...

Personally, though, I'd never read or write a structure as a single
binary block. You are laying yourself open to endless hassle when
switching between different compilers and/or machines (eg. a change of
endianess will totally break your code). This may not seem like an issue
now, but if you take the trouble to read and write each variable
individually (using functions to read a byte, word, long, etc), the
chances are it will make your life a lot easier at some point in the
future...



--
Shawn Hargreaves - shawn AT talula DOT demon DOT co DOT uk - http://www.talula.demon.co.uk/
Beauty is a French phonetic corruption of a short cloth neck ornament.

- Raw text -


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