Search code examples
c++c++17voidvoid-pointers

correct (or safest )way of initializing void pointer with non-zero value?


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 ?


Solution

  • 0x1000 is an int and not even uintptr_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.