0
class Node{
    int a;
    Node* next;
    Node():a(20),next(NULL){};
};

int main()
{
    Node* p = new Node;
    p->next = new Node;
    Node* q = p->next;

    **delete q; (or delete p->next;)**

    cout << q               << endl;        // always changed to "0000 8123"
    cout << &q->a           << endl;        // 0000 8123
    cout << &q->next        << endl;        // 0000 8127

    cout << q->a << q->next << endl;        // error!  why it is ok to access their address  and no to access their value? 

    cout << p->next        << endl;         // p->next no change , why ?
    cout << p->next->a     << endl;         // changed to "DDDD DDDD"
    cout << p->next->next  << endl;         // changed to "-5726 2307"

    return 0;
}

I know pointer p and q are on the stack, objects are on the heap.

delete q; q was changed to pointer an object in stack;
delete p->next; why was the value of p->next not changed?

What is the specific procedure of delete?

junlin
  • 1,835
  • 2
  • 25
  • 38
  • 1
    `why the value of p->next has no change?` Where did you read that the data that is pointed to must change when `delete` is called? It is highly possible that `delete` can be called on a pointer, and the data that is pointed to stays exactly the same as before. – PaulMcKenzie Apr 19 '15 at 06:19

2 Answers2

1

When you call delete q or delete p->next, the pointers are still pointing to locations in memory, but the object they point to are deleted. This is why if you print out the address of variable a in the object pointed to by q, it shows the memory location of that, same for next. But when you actually try to get the data from that object (dereferencing the pointer), the pointer points to garbage.

The proper way to go about it is to

delete q; q = nullptr;

0

The values in memory aren't cleared out. delete tells the program that it can use this block later on and override it with new allocations.

Your pointer still points to that block of memory, which can be overridden, which leads to unexpected errors further in your development process.

To prevent undefined behaviour - assign your pointer to nullptr after you delete your object.