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
To input and print a memory address, we use "%p" format specifier – which can be understood as "pointer format specifier". Program: In this program - first, we are declaring a variable named num and assigning any value in it. Since we cannot predict a valid memory address.
To print the memory address, we use '%p' format specifier in C. To print the address of a variable, we use "%p" specifier in C programming language. There are two ways to get the address of the variable: By using "address of" (&) operator.
Usually memory addresses are represented in hexadecimal. In c++ you can get the memory address of a variable by using the & operator, like: cout << &i << endl; The output of that cout is the memory address of the first byte of the variable i we just created.
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
.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With