Reputation: 4419
Assuming the value of uint32_t x
is an address. How can I get the value behind this address?
My try was to simply assign the address to a pointer.
int*y = x;
But x is not an int pointer, it's just int with an address as value.
Upvotes: 0
Views: 104
Reputation: 26800
In C++ this can be done using reinterpret_cast
8.5.1.10 Reinterpret cast [expr.reinterpret.cast]
...
5. A value of integral type or enumeration type can be explicitly converted to a pointer. A pointer converted to an integer of sufficient size (if any such exists on the implementation) and back to the same pointer type will have its original value; mappings between pointers and integers are otherwise implementation-defined. [Note: Except as described in 6.6.4.4.3, the result of such a conversion will not be a safely-derived pointer value. —end note]
And the rules in 6.6.4.4.3 state:
An integer value is an integer representation of a safely-derived pointer only if its type is at least as large as
std::intptr_t
and it is one of the following:
—(3.1) the result of a reinterpret_cast of a safely-derived pointer value;
—(3.2) the result of a valid conversion of an integer representation of a safely-derived pointer value;
—(3.3) the value of an object whose value was copied from a traceable pointer object, where at the time of the copy the source object contained an integer representation of a safely-derived pointer value;
—(3.4) the result of an additive or bitwise operation, one of whose operands is an integer representation of a safely-derived pointer value P, if that result converted byreinterpret_cast<void*>
would compare equal to a safely-derived pointer computable fromreinterpret_cast<void*>(P)
.
So if x
(in the question) has a type at least as large as std::intptr_t
and is already an integral representation of a safely derived pointer as per the rules above, you will be able to get the value behind the address stored in x
.
Upvotes: 2
Reputation: 238391
An integer type which is large enough to represent all data pointers can be converted into a pointer using reinterpret_cast
or an explicit conversion. The pointer can be indirected to get the pointed value using the indirection operator.
Note that uint32_t
is not guaranteed to be large enough to be able to represent all pointer values (and in fact will not be enough on modern 64 bit cpus). uintptr_t
is meant precisely for this purpose.
Note that if the pointed address does not contain an object (of compatible type), then behaviour will be undefined.
Upvotes: 3