-1
#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.

thinkdeep
  • 945
  • 1
  • 14
  • 32
  • 2
    Possible duplicate of [Why doesn't delete destroy anything?](http://stackoverflow.com/questions/3280410/why-doesnt-delete-destroy-anything) – HazemGomaa Nov 21 '16 at 03:58
  • 2
    "Delete" deallocates the memory at that location, it does not mean deleting the address value stored in the pointer. That is why setting it to NULL is recommended after deletion. – Mox Nov 21 '16 at 03:59
  • *But why does pstr2 still have valid address?* -- What would be an "invalid address"? – PaulMcKenzie Nov 21 '16 at 04:05
  • By valid, I mean that its address is unmodified. – thinkdeep Nov 21 '16 at 07:46
  • @H.G My question has overlap but have some difference as well – thinkdeep Nov 21 '16 at 07:47

1 Answers1

0
  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.

Galik
  • 47,303
  • 4
  • 80
  • 117