C++ - Safety of reinterpret_cast for pointer-to-primitives

828 views Asked by At

I've come across a piece of code in a project I'm evaluating, and wanted to know if the following cast is safe:

void func(unsigned long* input);
...
int data = 42;
func(reinterpret_cast<unsigned long*>(&data));  
// Casting to remove compiler warnings about data type not matching type expected

I know that with just simple C-style casting (ie: (unsigned long*)&data) that this is asking for trouble. Does reinterpret_cast automagically make this type of casting operating safe?

Thank you.

2

There are 2 answers

2
Bathsheba On BEST ANSWER

No it is not safe: the program behaviour is undefined.

This is because the pointer types are unrelated.

2
AudioBubble On

Any C-style cast gets interpreted as a particular C++-style cast. The C-style cast (unsigned long*)&data really means reinterpret_cast<unsigned long*>(&data). It's not possible for one of these to be safe when the other is unsafe.

And you're right, this is unsafe. Strictly speaking, it's generally not the cast itself that's the problem, although it could be. The cast itself is only a problem if data is not properly aligned for unsigned long. It's actually a subsequent access through the wrong type that's the problem. You don't show that access in your question, but unless func just casts input back to int *, or to char *, that's going to be a problem. And if func does cast it back like that, then it should just be declared to take the proper type.