Little problem with sizeof on PC

Noam Mendelson c60b-1eq at e260-1d.berkeley.edu
Tue Apr 23 15:07:47 AEST 1991


In article <1991Apr23.022057.29511 at ux1.cso.uiuc.edu> allender at ux1.cso.uiuc.edu (Mark Allender) writes:
>I'm having a litle problem that I have a suspicision about, but want
>to clarify.  Here's the situation....
>struct header {
> .........
>};
>Now, I want to read the beginning of a binary file into this structure,
>so I do something like this:
>	struct header Header;
>	if ((readnum = read(fd, (char *)(&Header), sizeof(Header)).....

Hmmm.  That should be:
   if ((readnum = read(fd, (struct header *)(&Header), sizeof(Header)) ...

>Things don't seem to get done correctly at this point.  A little investigation
>shows that sizeof(Header) return 202, and not 201.  This is clearly not
>what I want to do.

Your compiler probably word-aligned the structure (202 is on a word boundary).
Either that or your miscounted (I didn't verify your figure :-)
In any case, I suggest you check your compiler for a possible byte alignment
option (I know Turbo C 2.0 has this), and recompile.

>In any case, what is the best way around this problem.  Could I do something
>like
>	if ((readnum = read(fd, (char *)(&Header), sizeof(Header) - 1))....
>
>Seems like kind of a bad way to fix things....

That would probably work on a PC, assuming the structure was word-aligned.
But it's also dependent on your compiler.
The best thing would be to restructure the data file, using 202 byte blocks
instead of 201 to be on the safe side.  At worst, you're increasing the
size of the data file by about .5%.

-- 
+==========================================================================+
| Noam Mendelson   ..!ucbvax!web!c60b-1eq       | "I haven't lost my mind, |
| c60b-1eq at web.Berkeley.EDU                     |  it's backed up on tape  |
| University of California at Berkeley          |  somewhere."             |



More information about the Comp.lang.c mailing list