Search code examples
c++memory-managementvirtual-address-space

Can you delete dynamically allocated memory from a separate program?


This question is out of pure curiosity. I recently learnt that it is very important to delete memory space if it is dynamically allocated in the Heap. My question, is it possible to delete the dynamically allocated memory space using a different C++ program (from the one with which the memory space was created) if the address of the memory space is known?

Here's an example:

CODE01.CPP

#include <iostream>
using namespace std;

int main() {
    int *a = new int;
    cout << a;
    int foo;
    cin >> foo;  // for blocking the program from closing.
    return 0;
}

Output for CODE01.CPP (say)

0x7c1640

CODE02.CPP

#include <iostream>
using namespace std;

int main() {
    int *a = (int*)0x7c1640;
    delete a;
    return 0;
}

Will this work? If I first run code01.cpp and then immediately code02.cpp will the memory in the Heap get deleted?


Solution

  • Any modern OS will create a separate virtual address space for both of the programs. Thus the address you are printing in code01.cpp is only relevant for that program and you cannot access the address space from code02.cpp.

    So to answer your immediate question: running cpp02.cpp will not affect the state of the still running cpp01.cpp in any way.