Re: gcc structures

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



On 8 September 2013 11:10, JimJoycewrote:
> Is this a bug?

No.

> I'm coding in plain 'C'.
> I am trying to read and write GIS shapefiles.
> They start with a header of 9 ints and 8 doubles.
>
> So I used a structure eg:
> struct hdr { int g1[9]; double g2[8] }; struc;
>  fread ( struc, 100, 1, fp1);
> It was screwing up my doubles.
> --
> When, eventually, I experimented:
> sizeof(g1); sizeof(g2), sizeof (struc).
> I got 36, 64, 104.
> Note 104, not 100.
>
> Where is gcc placing the redundant 4 bytes?

Between the two arrays. The array of doubles is 8-byte aligned,
presumably because that's what your architecture requires.

> Is 'struct' insisting on a doubleword boundary?

For the double array, yes.  The C standard doesn't say struct members
must be adjacent, padding is allowed.

> NB I got round the problem by using 2 fread()s
> fread(struc.g1,36,1,fp1);
> fread(struc.g2,64,1,fp1);

That's the right thing to do.

You could also try this:

struct __attribute__((__packed__)) hdr { int g1[9]; double g2[8]; };

Although the compiler adds the padding for good reasons so it's best
not to force it to use a different layout unless you really need to.




[Index of Archives]     [Linux C Programming]     [Linux Kernel]     [eCos]     [Fedora Development]     [Fedora Announce]     [Autoconf]     [The DWARVES Debugging Tools]     [Yosemite Campsites]     [Yosemite News]     [Linux GCC]

  Powered by Linux