Pointers pointing to same memory location but different program

Viewed 287

I've written two programs, one (p1.cpp) that prints the value and address of a variable every 1 second..

// p1.cpp
int main() {

    int x = 13;
    int *p = &x;
    
    while (true) {
        cout << " value of x: " << *p << " addr: " << p << endl;
        sleep(1);
    }
}

and the other (p2.cpp), in which I manually point a pointer to the location printed out by p1.cpp and change the value.

//p2.cpp
int main() {
    
    int *p = (int*)0x61ff08; // this is manually set and compiled.
    cout << "value of p from p2.cpp : " <<  *p << endl;
    *p = 10;
    
}

However, upon running p1.cpp, setting the location and running p2.cpp, the value in first program doesn't seem to change. In fact, p2.cpp shows some garbage value if I display the contents of p.

output of p1.cpp

output of p2.cpp

I would like to know why is this happening and why the value of x isn't changed by the pointer of another program.

Thanks!

1 Answers

In modern operating systems like linux, windows or MacOs each process has its own virtual memory address space. Therefore the memory address from the process of your program p1 has nothing to do with the memory of the process of your program p2.

If you really want to access memory between processes directly you need to use shared memory.

But what is your intention? Do you just want to play around, or do you want communication between processes? In the later case you should read about IPC - inter process communication. There are a lot of IPC mechanisms you can use like named pipes, sockets or shared memory, depending on what you want to achieve.

You may have a look at this article for first introduction into the topic: https://en.wikipedia.org/wiki/Inter-process_communication

Related