The following works:
void* p = reinterpret_cast<void*>(0x1000);
But looks 'incorrect/unsafe' eg. 0x1000 is an int
and not even uintptr_t
, I could fix this, but is there a better/safer method of casting ?
const void is a type which you can form a pointer to. It's similar to a normal void pointer, but conversions work differently. For example, a const int* cannot be implicitly converted to a void* , but it can be implicitly converted to a const void* .
Explanation: Because the void pointer is used to cast the variables only, So pointer arithmetic can't be done in a void pointer.
yes it is safe.
0x1000 is an
int
and not evenuintptr_t
, I could fix this, but is there a better/safer method of casting
0x1000
is int
, and in reinterpret_cast<void*>(0x1000)
the compiler emits a sign extension instruction (sign is 0 here) or a plain register load instruction with an immediate operand to make the value as wide as void*
.
For many reasons the compiler cannot possibly know whether 0x1000
represents a valid address, so it has to comply and assume that it is a valid address.
Casting integers representing addresses to pointers with reinterpret_cast
is currently the existing practice.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With