Static_cast integer address to pointer
Asked Answered
A

4

14

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.
Averil answered 18/9, 2014 at 0:38 Comment(1)
You can also use reinterpret_cast which the C-style cast will eventually use anyway. Still not a good idea though.Anemic
G
32

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:

Type conversions

Gustavo answered 18/9, 2014 at 0:46 Comment(0)
M
4

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

  1. you are doing something dangerous there.
  2. you are doing something very seldom useful.
  3. you are doing something highly implementation-dependent.
  4. most times, that is simply a programming-error.

When should static_cast, dynamic_cast, const_cast and reinterpret_cast be used?
Regular cast vs. static_cast vs. dynamic_cast

Mumble answered 18/9, 2014 at 0:46 Comment(0)
O
4

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.

Obara answered 30/7, 2022 at 14:47 Comment(0)
E
1

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);
Editheditha answered 18/10, 2023 at 14:31 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.