Why does this code break strict-aliasing rules?

Jonathan Lennox jonathan@vidyo.com
Fri Nov 13 17:57:00 GMT 2009


> Jonathan Lennox wrote:
Andrew Haley writes:

> > I was under the impression it was valid to cast between a pointer to
> > a structure element and a pointer to the containing structure, so
long
> > as the underlying memory really is the containing structure -- this
is
> > how you can implement something equivalent to casting between C++
base
> > and derived classes, e.g.  Was I wrong?
> 
> That's not what you're doing here.  Of course, you can cast a
structure
> pointer to the type of its first element, and back.  But here you are
> casting a pointer to a type that the object to which it points does
not
> have:

I see.  So even though the ultimate type (through which I'm actually
accessing the pointer) really is the type of the structure's first
element, the fact that I'm casting through an "incorrect" intermediate
type causes strict-aliasing violations?

I find that if I annotate the derived_union type with
__attribute__((__may_alias__)), gcc 4.4 does not warn, and compiles my
code correctly.  Is this a correct use of may_alias?

-- 
Jonathan Lennox
Vidyo, Inc
jonathan@vidyo.com



More information about the Gcc-help mailing list