All Questions

621
votes
9answers
147971 views

What is the strict aliasing rule?

When asking about common undefined behavior in C, souls more enlightened than I referred to the strict aliasing rule. What are they talking about?
49
votes
3answers
3785 views

Why does optimisation kill this function?

We recently had a lecture in university about programming specials in several languages. The lecturer wrote down the following function: inline u64 Swap_64(u64 x) { u64 tmp; (*(u32*)&tmp...
23
votes
3answers
2560 views

Aliasing T* with char* is allowed. Is it also allowed the other way around?

Note: This question has been renamed and reduced to make it more focused and readable. Most of the comments refer to the old text. -- According to the standard, objects of different type may not sha...
41
votes
6answers
18790 views

gcc, strict-aliasing, and horror stories

In gcc-strict-aliasing-and-casting-through-a-union I asked whether anyone had encountered problems with union punning through pointers. So far, the answer seems to be No. This question is broader: D...
15
votes
3answers
2322 views

Strict aliasing rule and 'char *' pointers

The accepted answer to What is the strict aliasing rule? mentions that you can use char * to alias another type but not the other way. It doesn't make sense to me — if we have two pointers, one of ...
30
votes
7answers
11100 views

gcc, strict-aliasing, and casting through a union

Do you have any horror stories to tell? The GCC Manual recently added a warning regarding -fstrict-aliasing and casting a pointer through a union: [...] Taking the address, casting the resulting ...
49
votes
5answers
43858 views

"dereferencing type-punned pointer will break strict-aliasing rules" warning

I use a code where I cast an enum* to int*. Something like this: enum foo { ... } ... foo foobar; int *pi = reinterpret_cast<int*>(&foobar); When compiling the code (g++ 4.1.2), I get the...
20
votes
4answers
2080 views

float bits and strict aliasing

I am trying to extract the bits from a float without invoking undefined behavior. Here is my first attempt: unsigned foo(float x) { unsigned* u = (unsigned*)&x; return *u; } As I unders...
14
votes
1answers
1407 views

Does accessing the first field of a struct via a C cast violate strict aliasing?

Does this code violate strict aliasing? struct {int x;} a; *(int*)&a = 3 More abstractly, is it legal to cast between different types as long as the primitive read/write operations are type cor...
4
votes
4answers
2567 views

union for uint32_t and uint8_t[4] undefined behavior?

In the comments of this answer it is said that it would be undefined behavior to split up an integer into their bytes using a union like follows. The code given at that place is similar though not ide...

Previous Next