Using __attribute((packed))__ on picky architectures

Ian Lance Taylor iant@google.com
Fri Jan 16 16:34:00 GMT 2009


"Darren Rook" <route66@gmail.com> writes:

> the usage of __attribute__((packed)) on a structure is well
> documented, but I am curious about the ramifications of using this on
> an architecture that requires 16bit or 32bit alignment.
>
> For example:
>
> 	struct test
> 	{
>     	    UINT8  field1;
>     	    UINT16 field2;
>     	    UINT8  field3;
> 	} __attribute__((__packed__));
>
>    struct test t;
>
>    void handle(UINT16 *val)
>    {
>       // some code that works with val
>    }
>
>    handle(&t.field2);
>
> If this code is used on a 16bit architecture that does not implicitly
> allow 8bit addressing, the handle() function may cause an address
> exception because field2 may not be 16bit aligned because of the
> packing.

Yes.

> Is there some method to tell the compiler that *val may not be word
> aligned, so the compiler can generate code to work around the
> alignment issue (instead of assuming the *val will be word aligned)?

No.  Avoid writing this sort of code.

Ian



More information about the Gcc-help mailing list