views:

314

answers:

2
+3  A: 

No horror story of my own, but here are some quotes from Linus Torvalds (sorry if these are already in one of the linked references in the question):

Type-based aliasing is stupid. It's so incredibly stupid that it's not even funny. It's broken. And gcc took the broken notion, and made it more so by making it a "by-the-letter-of-the-law" thing that makes no sense.

...

I know for a fact that gcc would re-order write accesses that were clearly to (statically) the same address. Gcc would suddenly think that

   unsigned long a;

   a = 5;
   *(unsigned short *)&a = 4;

could be re-ordered to set it to 4 first (because clearly they don't alias - by reading the standard), and then because now the assignment of 'a=5' was later, the assignment of 4 could be elided entirely! And if somebody complains that the compiler is insane, the compiler people would say "nyaah, nyaah, the standards people said we can do this", with absolutely no introspection to ask whether it made any SENSE.

Michael Burr
+1. But gcc will usually (hopefully always?) give a warning in this example.
Joseph Quinsey
And one _possible_ solution to Linus's complaint is: `#define CAST(type, x) (((union {typeof(x) src; type dst;}*)`
Joseph Quinsey
IMO, Linus seems to be the one who is stupid here.
Alok
The first one is definitely a bug (caused by the compiler's inlined implementation of `malloc` falling foul of its own strict aliasing rules!).
caf
@Michael: Thank you for your answer, and I guess I'll accept it eventually. But it sad there are no other answers after four days.
Joseph Quinsey
@Alok see the second link, the compiler really is slightly insane with `-fstrict-aliasing`
Spudd86
A: 

The following code returns 10, under gcc 4.4.4. Is anything wrong with the union method or gcc 4.4.4?

int main()
{
  int v = 10;

  union vv {
    int v;
    short q;
  } *s = (union vv *)&v;

  s->v = 1;

  return v;
}