Weird structure alignment on GCC 4.2

Ian Lance Taylor iant@google.com
Mon Sep 29 16:59:00 GMT 2008


"andrew wiggin" <end3er@gmail.com> writes:

> struct _s1 {
>     unsigned char e1;
>     unsigned char e2;
> };
>
> struct _s2 {
>     void e1;
>     struct _s2 e2[2];
>     void e3;
> };

This code doesn't compile.  For discussing issues like this it helps
to see the exact code.

> The result is that with no packing attribute, the line "struct _s2
> e2[2];" will be interpreted as ".align 4 / .byte / .byte .align 4 /
> .byte / .byte" however there is absolutely no reason why this
> alignment in the middle of the structure happens. The problem when
> using the "packed" attribute is that most of the 16bits elements will
> be considered as 2 8bits elements and 32 bits elements will be
> considered as 4 8bits elements which is absolutely not what I want as
> these structures are mapped on internal registers that must be written
> in an atomic instruction.
>
> So the question is, what did I miss ? Is it the intended behavior for
> GCC >= 4.2 or does a patch already exist for fixing that.

Struct layout is specified by the processor ABI, so that different
compilers for the same processor can interoperate.  When I compile
this code:

struct _s1 {
    unsigned char e1;
    unsigned char e2;
};

struct _s2 {
    void *e1;
    struct _s1 e2[2];
    void *e3;
};

struct _s2 v = { 0, { { 1, 2 }, { 3, 4 } } , 0 };

for the x86, then I do not see the alignment you mention.  So you need
to tell us what target you are using.

Ian



More information about the Gcc-help mailing list