Assigning A Specific Memory Address from another program, and changing it's value
c++, memory, memory-address, variable-assignment
Solution
The short answer is that different processes use completely different address spaces. Without doing a lot more work, process B can't read or write the memory from process A.
It is possible to do this, in a platform-specific way. Win32 offers functions such as WriteProcessMemory where you can directly poke values into the memory space of another process. Most operating systems offer a shared memory function, with Win32 you can use memory mapped files and Unix flavours typically have some kind of equivalent "mmap" or "shmem" feature.
Problem
Recently I've time off of school for a few days and wanted to do a small program(s) experiment in C++ dealing with memory address. I wanted to see is that if a currently running program (Let call it Program A) that created a pointer to an int object in the heap, can be seen by another program and be modified (Program B). So for Program A, this is my basic code: ``` // Program A #include <iostream> using namespace std; int main() { // Pointer to an int object in the heap int *pint = new int(15); // Display the address of the memory in heap cout << pint << endl; // Display the value stored in that address cout << *pint << endl; return 0; } ``` Output for Program A: ``` 0x641030 15 ``` For Program B, I looked at how to assigned a specific memory address through this link: http://www.devx.com/tips/Tip/14104 The code for Program B is: ``` // Program B #include <iostream> using namespace std; int main() { // assign address 0x641030 to p int *p = reinterpret_cast< int* > (0x641030); cout << p << endl; cout << *p << endl; return 0; } ``` Output for Program B: ``` 0x641030 ... "Crash" ``` I don't quite understand it. I was expecting a display of 15 from `*p`, but it did something i didn't expect. I also tried to assign `*p` to a number like `*p = 2000` but it crashed when I attempted that as well. Also when I display the address of the pointers and Program A (`cout << &pint;`) and for Program B (`cout << &p;`), they both showed the same memory address. Does anyone know what is going on exactly? I'm interested yet confused of what is happening. Also, is it possible for me to do what I am attempt in C++/C ? ** EDIT ** Sorry to not mention my platform, but I am currently using Window 7 Professional