3

Is it true that reinterpret_cast wont change the values of the pointer it cast, even if the new pointer is a illegal one:

char * charbuffer = ....//charbuffer is a buffer we allocated.

int * Ptr=reinterpret_cast< int *>(charbuffer+17);//Ptr should be illegal due to mis-aligment

I assume even if the address pointed by charbuffer+17(which is char * pointer type) is a illegal one to store values of int type due to mis-alignment, Ptr get by reinterpret_cast is still pointed to the same memory address as charbuffer+17?

Note that we don't care about the contents it pointed to, we just want to make sure the memory address this pointer represents is the same as charbuffer+17.

Such promise is very important for the correctness and portability of some piece of codes we reviewed.

5
  • Why do you think the pointer would be illegal? That depends on the architecture. It's perfectly valid on many architectures to point to whatever memory location, it just might be slower. Jan 31, 2017 at 12:32
  • Well, not should, but could. Jan 31, 2017 at 12:33
  • In any case there's no reason for casting to change the value. If it's not allowed to be used then there will be a hardware exception, interrupt or some other way of reporting an error. It's not the language's job to determine if it's allowed, especially since it might never even be accessed. Jan 31, 2017 at 12:36
  • I just hope this is indeed the case. Jan 31, 2017 at 12:37
  • Possible duplicate of Should I worry about the alignment during pointer casting? Jan 31, 2017 at 12:42

1 Answer 1

2

According to the C++ standard, it is not safe:

5.2.10 Reinterpret cast
[...]
3 [ Note: The mapping performed by reinterpret_cast might, or might not, produce a representation different from the original value. — end note ]

But in practice I would not expect reinterpret_cast to return another value.

1
  • You're welcome. I think if the pointer is cast back to the original type, the value will be the same again, but I didn't find the place in the standard - If this would be useful for you, I can try to find it.
    – alain
    Jan 31, 2017 at 12:50

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.