0
struct S { char A; char B; char C; char D; };
unsigned char x[4] = { 0xDE, 0xAD, 0xBE, 0xEF };
auto y = (S*) x;
cout << y->A; // undefined behaviour

The fourth line here violates strict aliasing, which means that the compiler could decide to play some mean tricks on me. Is there any way to achieve something similar without invoking undefined behaviour?

Carl Patenaude Poulin
  • 6,238
  • 5
  • 24
  • 46
  • 4
    The third line does not violate strict aliasing yet. But it would if you later wrote `*y = z;` for example. If you intend to do something like that it'd be good to have it in the question - as it stands now, your answer is wrong (casting is not undefined behaviour per se). – M.M Oct 13 '16 at 01:45
  • You should not cast a `char*` to a `struct*`, you should cast the `struct*` to a `char*` then `copy`. – Galik Oct 13 '16 at 02:09
  • I don't think violating strict aliasing means that the compiler may play some mean tricks. In fact compilers (like gcc and clang) provide an option -fno-strict-aliasing that allows you to tell the compiler strict aliasing is not observed in the program. See [this question](http://stackoverflow.com/questions/754929/performance-benefits-of-strict-aliasing) for example. – esam Oct 13 '16 at 13:45
  • I am a bit confused with your question, as I don't understand the problem you're facing. What is the behaviour that you are expecting when casting char pointer to struct pointer? – call me Steve Oct 13 '16 at 18:56

1 Answers1

1
  • Casting and dereferencing is undefined behavior.
  • Union casting is kosher... in C. In C++ it's undefined behavior.
  • reinterpret_cast is undefined behavior.

The only legit approach is memcpy. A sufficiently smart compiler will optimize it into nothingness, but you really have no guarantees.

Carl Patenaude Poulin
  • 6,238
  • 5
  • 24
  • 46