Subject: Re: Intermediate void* casts
To: Manuel Bouyer <bouyer@antioche.lip6.fr>
From: Frederick Bruckman <fredb@immanent.net>
List: tech-misc
Date: 08/10/2003 15:15:12
On Sun, 10 Aug 2003, Manuel Bouyer wrote:
> On Sun, Aug 10, 2003 at 06:35:58PM +0200, Martin Husemann wrote:
> > [...]
> > - Removing the (void*) causes gcc 3.3.1 to warn about strict alias violations
> > by type-punned pointer dereferences.
>
> Pardon my ignorance, but could you explain what is a "strict alias violations
> by type-punned pointer dereferences" ? Is it something new with gcc3 ?
The error in question is this:
warning: dereferencing type-punned pointer will break strict-aliasing rules
and yes, it's new with gcc3. Since no one else has stepped up,
I'll try to explain what I think it means, and perhaps someone
knowledgable will clarify:
A type-punned pointer is a pointer to one type of thing that's
interpreted as another, as when you store a packet of undifferentiated
"char *" data, then access it as either one type of struct, or a
completely different type, depending on some other datum, perhaps even
something contained in the packet. Of course you're allowed to do that
in C. The problem is, that the compiler would like to assume that,
say, a quad in a struct declared in a translation unit is suitably
aligned for the fancy new instructions that only work on suitably
aligned quads, but it can't, if the storage was actually defined in
another translation unit as an array of char's.
There are at least four ways to fix the warning:
1) If you know that all the ways you access the data are compatible
(for the purposes of optimization, if not in the strictest C sense),
then it's OK to cast away the warning. I have a feeling folks are
going to do this without begin sure it's OK. (I'm not sure, myself,
when's it OK.)
2) You could make the definition a union type, as union types are
supposed to be suitably aligned for all the components. "Suitably
aligned", however, used to mean "aligned so that it'll work at all".
Interpreting it to mean "align in the most effecient way" has the
potential to break ABI compatibility in mysterious ways, so I don't
think they're actually doing that yet. Maybe that's why this seems
to be the least popular option.
3) You could turn off strict-aliasing, with -fno-strict-aliasing.
This would seem to be the safest, but you then lose all the benefits
of strict-aliasing (whatever that means).
4) You can bury your head in the sand, with -Wno-strict-aliasing.
Frederick