Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to modify object knowing memory adress in c++?

Good evening.

I opened Visual Studio 2012 and run program doing this:

    double x = 8768130;
    cout << &x;

    cin.get();
    return 0;

Address it wrote in console was 003CFBF8.

Then, I opened another copy of Visual Studio and tried to read this, but I am not sure if I am doing it correctly. I was already searching in Stack Overflow before posting it and find out that I should do something like that:

    double* ptr = reinterpret_cast<double*>(0x003CFBF8);

    cout << *ptr;

but it produced exception

Unhandled exception at 0x00A943DD in Project2.exe: 0xC0000005: Access violation reading location 0x003CFBF8.

What does that mean? I have no access? I did it in wrong way?

If you ask me why I want to do that, I am learning C++ from some of books and I wanted to check how volatile works. This is why I wanted to:

  • open first program, initialize variable, write it's address;
  • open second program and modify what written address relates to
  • write variable in first program to check if everything is okay.
like image 936
Kusavil Avatar asked Jan 10 '23 20:01

Kusavil


1 Answers

... I opened another copy of Visual Studio ...

and there lies your problem. All modern systems use virtual memory, which means one process is not allowed to touch another process's virtual address space. This is enforced by the processor.

You could potentially do this within the same process (program). However, modern OSes also enable ASLR (Address Space Layout Randomization) which means that a piece of code or data will likely load at a different virtual address, every time the program is executed.

If you want to access the memory of another process, your best bet is probably to use your OS's debugging APIs. Specifically, on Windows you can call WriteProcessMemory.

If you just want to play with volatile (where memory might change out from underneath you), you should consider spawning another thread, who periodically modifies a globablly-accessible variable.

like image 85
Jonathon Reinhart Avatar answered Jan 21 '23 10:01

Jonathon Reinhart