Why do you need a C-style cast for the following?
int* ptr = static_cast<int*>(0xff); // error: invalid static_cast from type 'int'
// to type 'int*'
int* ptr = (int*) 0xff; // ok.
Why do you need a C-style cast for the following?
int* ptr = static_cast<int*>(0xff); // error: invalid static_cast from type 'int'
// to type 'int*'
int* ptr = (int*) 0xff; // ok.
static_cast
can only cast between two related types. An integer is not related to a pointer and vice versa, so you need to use reinterpret_cast
instead, which tells the compiler to reinterpret the bits of the integer as if they were a pointer (and vice versa):
int* ptr = reinterpret_cast<int*>(0xff);
Read the following for more details:
You need a C-style cast or directly the reinterpret_cast
it stands for when casting an integer to a pointer, because the standard says so for unrelated types.
The standard mandates those casts there, because
When should static_cast, dynamic_cast, const_cast and reinterpret_cast be used?
Regular cast vs. static_cast vs. dynamic_cast
Being late to the party I found that the following works only using static casts:
int* ptr1 = static_cast<int*>(static_cast<void*>(static_cast<unsigned char*>(nullptr) + 0xff));
This way you don't translate the constant directly to a pointer, instead you add it as a bytewise offset to the nullptr.
CppCoreGuidelines discourage the use of reinterpret_cast
and the static analysis tool that we're using enforces that.
Since we need to turn machine addresses into pointers, I tried xmoex's solution, but that leads to this warning: "arithmetic on a null pointer treated as a cast from integer to pointer is a GNU extension".
So I found out that to cheat the compiler, you just have to extract static_cast<unsigned char*>(nullptr)
in a variable.
I came out with this small template function:
template<typename T, typename P>
constexpr auto numberToPointer(T value) -> P*
{
unsigned char* ucharnullptr = nullptr;
return static_cast<P*>(ucharnullptr + value);
}
To be used like this:
unsigned int u = 0x123;
void* ptr = numberToPointer<unsigned int, void>(u);
© 2022 - 2024 — McMap. All rights reserved.
reinterpret_cast
which the C-style cast will eventually use anyway. Still not a good idea though. – Anemic