I am designing a game engine and a lot of subsystems would interface with each other better if deleted pointers could be detected. I decided to take a look at what the actual memory address points to. It appears to point to 0000000000008123 in my PC. I wonder, does it points to the same memory address to anyone else. If it does, would it point to the same memory address in other operating systems? It most likely varies from PC to PC, but maybe storing what that actual value is at the beginning of the program could be helpful to detect deleted memory. Could this be a trustworthy method to detect deleted memory in C++? Here is the test case I used:
#include <iostream>
using namespace std;
int main() {
cout << "Program operating..." << endl;
for (unsigned int i = 0; i < 5; i++) {
int* integer1 = nullptr;
int* integer2 = nullptr;
int* integer3 = nullptr;
int* integer4 = nullptr;
int* integer5 = nullptr;
integer1 = new int(1);
integer2 = new int(2);
integer3 = new int(3);
integer4 = new int(4);
integer5 = new int(5);
cout << integer1 << endl;
cout << integer2 << endl;
cout << integer3 << endl;
cout << integer4 << endl;
cout << integer5 << endl;
cout << endl;
delete integer1;
delete integer2;
delete integer3;
delete integer4;
delete integer5;
cout << integer1 << endl;
cout << integer2 << endl;
cout << integer3 << endl;
cout << integer4 << endl;
cout << integer5 << endl;
cout << endl;
}
cout << "Program terminated..." << endl;
}
Output
0000000000008123
0000000000008123
0000000000008123
0000000000008123
0000000000008123
Smart pointers do exactly what you are looking for with the advantage that they will reclaim memory as objects go out of scope.
You can query them to check if they are empty or not.
Example: https://godbolt.org/z/6s5vxrjsa
Note that you do not need to
delete
the object. They will be deleted automatically. This example shows this: