In message <>
CBFalconer <> wrote:
> Eric Smith wrote:
> > Ah! So the compiler can't add padding bytes for alignment. I
> > had the mistaken impression that it was permissible for the
> > compiler to add padding. For instance, on an architecture with
> > four-byte integers required to be four-byte aligned, I thought
> > some padding might be used in a case like this:
> >
> > struct foo_t { int a; char b; }; /* sizeof(struct foo_t) == 5 */
> >
> > struct foo_t bar [12];
> >
> > I'd previously expected that to result in the size of the array
> > being 96 bytes, but based on the array definition you've quoted
> > (6.2.5#20), apparently it would only be 60 bytes. I suppose the
> > compiler would be required to generate appropriate code for the
> > misaligned integers, or to make sizeof(struct foo_t) be a
> > multiple of four.
>
> You were right the first time. It doesn't pad between array
> elements, but the elements themselves are padded so that they
> don't need it. That 5 above is probably 8.
Indeed, but as we were originally talking about flexible array members, it's
worth noting one possible implementation quirk:
struct foo_t { int a; char b; }; /* sizeof(struct foo_t) == 8 */
struct jim_t { int a; char b; char c[1]; }; /* sizeof(struct jim_t) == 8 */
struct bar_t { int a; char b; char c[]; } /* sizeof(struct bar_t) == 5 */
That's quite possible, and a logical way to implement flexible array members.
(The alternative would be to add 3 bytes of padding between b and c in
bar_t). Structures with flexible array members cannot be elements of arrays,
so trailing padding is not needed to ensure alignment of the int. Our
implementation works in this way.
FWIW, this is one of gcc's non-conformances to C99 - its sizeof(struct bar_t)
== 8, but offsetof(bar_t, c) == 5.
--
Kevin Bracey, Principal Software Engineer
Tematic Ltd Tel: +44 (0) 1223 503464
182-190 Newmarket Road Fax: +44 (0) 1223 503458
Cambridge, CB5 8HE, United Kingdom WWW:
http://www.tematic.com/