2

If I have C program called A with the following code:

int main()
{
   int x=5; 
   int *pX=&x;
   return 0;
}

pX point to address of x, Let's say is 0x123456.

And I have another program called B:

int main()
{
   int y=5; 
   return 0;
}

And let's say the address of y is 0x123488 how does the mechanism (virtual memory) that prevent me to change the value of pX to point on 0x123488 (address of y) and to read/change the value of y from program A if I know the address of y work?

NOTE: Let's assume I debug both programs and I know the current address for each value.

2 Answers2

2

You can't. Each process has a virtual address space, that's independent from each other. If you want two different processes to communicate look up IPC

The kernel takes care of this, by actually allocating in different parts of memory the two programs, and then providing each process the illusion of having their own memory (virtual memory)

If you want to know the very details of how this abstraction is implemented, I'd suggest you to read the chapter on 'Address spaces' (13) and 'Address translation' (15) from the book Operating system: three easy pieces.

It's free!

ovalb
  • 555
  • 6
  • 15
  • That is only if your OS uses an MMU (ok, that is probably the case in 99% of systems). But even then, you can probably alloc some shared memory, for example via `mmap()` and `MAP_SHARED`. Shared memory is a form of IPC. – 12431234123412341234123 Aug 10 '21 at 17:31
2

And let's say the address of y is 0x123488 which mechanism prevent me to change the value of pX to point on 0x123488 (address of y) and to read/change the value of y from program A if I know the address of y?

It is the virtual address space.

Meaning that while your code sees the address of y to be 0x123488 that is only the virtual address of y in the context of your program. The actual physical address is managed by the OS(more specifically, the kernel).

However the good news is that you can change the variable of another process. All of the interaction between two processes must be done through your OS's API.

A lot of debugging programs and game cheats use this method to debug or well, cheat at the game(do not attempt, the anti-cheat will detect this method and ban you)

For windows you can use WriteProcessMemory and ReadProcessMemory. I don't know how to do it on Linux but I am sure there is a way.

Also as onVal mentioned in his answer, you should look up Inter Process Communication as it might be more useful.

Marko Borković
  • 1,884
  • 1
  • 7
  • 22