This is the mail archive of the gcc-help@gcc.gnu.org mailing list for the GCC project.


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]
Other format: [Raw text]

RE: Why does this code break strict-aliasing rules?


John S. Fine wrote:

> Jonathan Lennox wrote:
> >
> > Am I missing something, or is gcc mis-compiling correct code?
> >
> gcc is correct.
> 
> You put a value into union derived_union* u and then read a value out
> of ((struct base*)u)
> 
> That is a violation of strict aliasing.
>
> Annoying as it is, the compiler is free to assume the value you put in
> is unrelated to the value you read, so the value you put in u is never
> used, so the optimizer can remove that operation.

But I didn't put a value into derived_union* u -- every time I
initialize, read, or write the structure, I'm accessing it via a 'struct
base' or 'struct base *'.  The function call just casts to a
derived_union*, and then casts back.

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?

> Why do you want to cast the union pointer rather than just use it?
> 
> I understand you are relying on the fact that the base part of each of
> derived1 and derived2 will be the first thing in the union, so without
> strict aliasing your code would be correct.  But as long as you rely
on
> that placement it is simpler and more correct to just use
> u->d1.base.a = a;

My original code just used the union pointer, as you suggested, but that
also gave a strict-aliasing warning.  Since I really don't have a
'struct derived1' present, I thought that skipping the intermediate type
would avoid the problem, but apparently it doesn't.  (I get the same
strict-aliasing error with your suggested change.)

Is there any convenient way to get this code to work reliably, without
either restructuring my objects or having to use the big hammer of
-fno-strict-aliasing?

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


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]