#include <iostream>
#include <string>
using namespace std;
int main() {
string* pstr2 = new string;
cout << "pointer pstr2: " << pstr2 << endl;
delete pstr2;
cout << "pointer pstr2 after deletion: " << pstr2 << endl;
string* pstr = new string;
pstr->push_back('a');
cout << "pointer pstr: " << pstr << endl;
cout << "*pstr: " << *pstr << endl;
delete pstr;
cout << "pointer pstr after deletion: " << pstr << endl;
cout << "*pstr after deletion: " << *pstr << endl;
return 0;
}
The output is as follows:
pointer pstr2: 0x7ffe00404d10
pointer pstr2 after deletion: 0x7ffe00404d10
pointer pstr: 0x7ffe00404d10
*pstr: a
pointer pstr after deletion: 0x7ffe00404d10
*pstr after deletion: a
Questions:
I know there is a practice to set dynamic pointer to NULL after deleting the pointer. But why does pstr2 still have valid address?
Deleting pointer pstr frees the memory, i.e., "a". But why does *pstr still have valid content as "a"?
Why does pstr and pstr2 have the same allocated address? I have run the code for several times.