简体   繁体   中英

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.

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

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 (ie pointers to 32-bit integers should be aligned on 4-byte boundary).

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.

You must cast 0x220202 to int*

Write :

p = (int*)0x220202 ;

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

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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM