coder coder - 18 days ago 6
C++ Question

C++ delete pointer

#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:


  1. I know there is a practice to set dynamic pointer to NULL after deleting the pointer. But why does pstr2 still have valid address?

  2. Deleting pointer pstr frees the memory, i.e., "a". But why does *pstr still have valid content as "a"?

  3. Why does pstr and pstr2 have the same allocated address? I have run the code for several times.


Answer
  1. I know there is a practice to set dynamic pointer to NULL after deleting the pointer. But why does pstr2 still have valid address?

It doesn't have a "valid" address. By deleting the memory at that address you invalidated it. The address does not change but the memory that was allocated to that address has been unassigned and may be overwritten/removed at any time.

  1. Deleting pointer pstr frees the memory, i.e., "a". But why does *pstr still have valid content as "a"?

The content is not "valid" it just happens to not have changed. There is no guarantee of that. Deleting the memory does not necessarily change its contents. It may just mark it as available to another variable.

  1. Why does pstr and pstr2 have the same allocated address? I have run the code for several times.

That's just a coincidence. Its not guaranteed to always be the same. If it is its an artifact of the way the memory allocation functions works for that speific compiler implementation.