8

I was wondering whether it is possible to do something like this:

unsigned int address = 0x0001FBDC; // Random address :P
int value = *address; // Dereference of address

Meaning, is it possible to get the value of a particular address in memory ?

Thanks

Matt
  • 22,721
  • 17
  • 71
  • 112
Zyyk Savvins
  • 483
  • 4
  • 8
  • 14

1 Answers1

21

You can and should write it like this:

#include <cstdint>

uintptr_t p = 0x0001FBDC;
int value = *reinterpret_cast<int *>(p);

Note that unless there is some guarantee that p points to an integer, this is undefined behaviour. A standard operating system will kill your process if you try to access an address that it didn't expect you to address. However, this may be a common pattern in free-standing programs.

(Earlier versions of C++ should say #include <stdint.h> and intptr_t.)

Kerrek SB
  • 464,522
  • 92
  • 875
  • 1,084
  • In this case is there any difference between the c-style cast that OP uses and the `reinterpret_cast`? I think the latter just decays to the former in this case? – Alok Save Sep 06 '12 at 10:43
  • +1 for fixing the type mismatches, but yes, of course it will work, (with your caveat re. addressability, memory-management protections etc), else pointers would be unuseable! – Martin James Sep 06 '12 at 10:45
  • @Als: Rather, the C-style cast decays to the `reinterpret_cast`. The meaning of C-style casts in C++ is defined in terms of the C++-style casts IIRC. As far as the compiler is concerned a C-style cast in C++ is normally just a way of saying, "um, I'm not sure what cast I want here, I'll take the chef's choice". I say normally because I think there are some dubious things you can do with a C-style cast but not with C++-style casts: casting bounder-to-derived to pointer-to-private-base or something. – Steve Jessop Sep 06 '12 at 10:45
  • @SteveJessop:True.Eitherway, the point is that both are same in this case or is there anything that I missed, which makes `reinterpret_cast` any better. – Alok Save Sep 06 '12 at 10:49
  • @Als: I don't believe you have missed anything. – Steve Jessop Sep 06 '12 at 10:50
  • Why `intptr_t` in earlier versions of C++? `intptr_t` and `uintptr_t` were added to the standards at the same time. (On the other hand, since this sort of thing is obviously not portable, you might as well go ahead and use `unsigned`, if that's the correct size. Or not... I like the documentation impact of `uintptr_t` anyway.) – James Kanze Sep 06 '12 at 11:25