Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ - Get value of a particular memory address

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

like image 739
Zyyk Savvins Avatar asked Sep 06 '12 10:09

Zyyk Savvins


People also ask

How do I print a value in a memory address?

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.

How can we get its address in memory in C?

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.

How do you access the memory address of a variable?

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.


1 Answers

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.)

like image 83
Kerrek SB Avatar answered Sep 21 '22 17:09

Kerrek SB