In my project we have a piece of code like this:
// raw data consists of 4 ints
unsigned char data[16];
int i1, i2, i3, i4;
i1 = *((int*)data);
i2 = *((int*)(data + 4));
i3 = *((int*)(data + 8));
i4 = *((int*)(data + 12));
I talked to my tech lead that this code may not be portable since it’s trying to cast a unsigned char* to a int* which usually has a more strict alignment requirement. But tech lead says that’s all right, most compilers remains the same pointer value after casting, and I can just write the code like this.
To be frank, I’m not really convinced. After researching, I find some people against use of pointer castings like above, e.g., here and here.
So here are my questions:
- Is it REALLY safe to dereference the pointer after casting in a real project?
- Is there any difference between C-style casting and
reinterpret_cast? - Is there any difference between C and C++?
If the pointer happens to not be aligned properly it really can cause problems. I’ve personally seen and fixed bus errors in real, production code caused by casting a
char*to a more strictly aligned type. Even if you don’t get an obvious error you can have less obvious issues like slower performance. Strictly following the standard to avoid UB is a good idea even if you don’t immediately see any problems. (And one rule the code is breaking is the strict aliasing rule, § 3.10/10*)A better alternative is to use
std::memcpy()orstd::memmoveif the buffers overlap (or better yetbit_cast<>())Some compilers work harder than others to make sure char arrays are aligned more strictly than necessary because programmers so often get this wrong though.
http://ideone.com/FFWCjf
It depends. C-style casts do different things depending on the types involved. C-style casting between pointer types will result in the same thing as a reinterpret_cast; See § 5.4 Explicit type conversion (cast notation) and § 5.2.9-11.
There shouldn’t be as long as you’re dealing with types that are legal in C.
* Another issue is that C++ does not specify the result of casting from one pointer type to a type with stricter alignment requirements. This is to support platforms where unaligned pointers cannot even be represented. However typical platforms today can represent unaligned pointers and compilers specify the results of such a cast to be what you would expect. As such, this issue is secondary to the aliasing violation. See [expr.reinterpret.cast]/7.