What's the problem with using reinterpret_cast in C++?

Question:

I know using reinterpret_cast can cause undefined behavior, but I still don't understand why (I know it has something to do with object lifecycle and memory alignment). I would like to see some practical example where casting would result in undefined behavior.

Answer:

With it you can cast a pointer of any type to any other type, it is similar to the normal C cast, the one with (parentheses*).

Their main problem is that the compiler has no way of checking if the conversion makes sense. It's at the developer's own risk, and it's very easy to make a mistake.

For example, converting a pointer to an integer (int or long int), and then back to a pointer, can generate undefined behavior. This works on many architectures, but not all. There are 32-bit architectures with 64-bit pointers, int is 32-bit on 64-bit Linux, and so on.

Converting a char* pointer to double* is undefined behavior. It works on architectures where a double (64 bits or 8 bytes) can occupy any memory address, but many architectures insist that double* points to a multiple of 8. (A correct way to access an unaligned double is to copy it to a local variable using memcpy(), and then using the double local variable.)

On some architectures, pointers can have different sizes according to the type they point to, so it can take a while to convert from Type* to void* and back to Type*.

Scroll to Top