Idrizi.A
Idrizi.A

Reputation: 12010

Can I read any memory value

I am just curious to know if I can read any value in memory by providing it's address (in my case random). I knew it won't work but I tried:

int e = 10;
int* p = &e;
p = 0x220202;

This won't even compile. So, is there a way to read something in my computer's memory in C++ or any other programming language.

Upvotes: 2

Views: 7358

Answers (5)

lethal-guitar
lethal-guitar

Reputation: 4519

So, is there a way to read something in my computers memory

If you refer to your computer's entire memory: No, you cannot - at least not on modern desktop/mainstream operating systems. You can only read memory from your process' address space.

Have a look at virtual memory. In a nutshell: Your pointers refer to "virtual" addresses, not real ones. Special hardware in your computer translates these addresses into real addresses. The operating system defines how the mapping has to be done. This way, each process has it's own unique address space. Whenever the OS's scheduler switches to another process, it tells the hardware to switch to the corresponding translation table. Thanks to this mechanism, you get isolation between processes, which is a very good thing: If a poorly programmed application accesses invalid memory, only the process in question will crash, whereas the rest of your system is not affected.

Think about it: Without this isolation, you would potentially need to restart your computer every time you're testing some pointer arithmetic..

Upvotes: 9

ArtemB
ArtemB

Reputation: 3622

You can read any value that operating system allocated to your process.

In case of your example you need to typecast an integer to a pointer before assigning it:

p = (int*) 0x220202; // now p points to address 0x220202
int value = *p;  // read an integer at 0x220202 into 'value'

Note that not addresses will be accessible -- some areas are read-only, on some platforms the pointer must also be properly aligned (i.e. pointers to 32-bit integers should be aligned on 4-byte boundary).

Upvotes: 3

Logan Murphy
Logan Murphy

Reputation: 6230

You will get a runtime error since this memory is outside the scope of your program

#include <iostream>
using namespace std;

int main() {
    int * p = (int *) 0x220202;
    int i = *p;
    cout << i;
    return 0;
}

Upvotes: 0

Jabberwocky
Jabberwocky

Reputation: 50775

You must cast 0x220202 to int*

Write :

p = (int*)0x220202 ;

This will compile, but it will most likely crash when you run the program.

Upvotes: 0

Prabhu
Prabhu

Reputation: 3528

You code will compile if you replace p = 0x220202 with p = (int *)0x220202. You will not be able to access ANY memory just by providing an address. You can access only the memory within the address space of this process. Meaning your OS will simply prevent you from accessing another exe's memory.

Upvotes: 0

Related Questions