简体   繁体   中英

Is this deleting pointer behavior normal?

#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
#include <unordered_map>
#include <unordered_set>
#include <cmath>

using namespace std;

template <class T>
class binary_node {
public:
    T data;
    binary_node<T> *left;
    binary_node<T> *right;

    binary_node(const T& data)
        :data(data), left(NULL), right(NULL) {
    }
};

int main() {
    binary_node<int>* node = new binary_node<int>(10);
    node->left = new binary_node<int>(1);
    node->right = new binary_node<int>(50);

    binary_node<int>* ptr = node->left;

    delete ptr;
    ptr = NULL;

    if (node->left == NULL) {
        cout << "????";
    }
    else {
        cout << node->left->data << endl;
    }   

    return 0;
}

I would expect node->left == NULL , but the result is totally unexpected even though the data of node->left is garbage. I'm using Visual C++ 2010, could anyone help me explain this behavior?

EDIT
On the other hand, it works just fine when traversing and delete node by node like this:

    ~linkedlist() {
#if DEBUG
        cout << "~linkedlist() called.\n";
#endif
        while (head != NULL) {
#if DEBUG
            cout << "delete node: " << head->data << '\n';
#endif
            node<T>* temp = head;
            head = head->next;
            delete temp;
            temp = NULL;
        }
    }

You are deleting the the data allocated to node->left object ie. the new binary_node<int>(50) object.

However you are deleting via another pointer. You then NULL that other pointer

node->left is never set to null. As such the contents of whatever it points (deallocated memory) is is what it points to.

try this:

binary_node<int>** ptr = &(node->left); 

delete *ptr; 
*ptr = NULL; 

Or this

delete node->left; 
node->left = NULL; 

Here is an improved depiction I made to show what I'm saying: 在此处输入图片说明

You have to set node->left to NULL instead of ptr to NULL .

delete will not set the pointer passed in to NULL . Even if it does, it will not be able to modify node->left

Pointer is actually just a number. Number which determines a place in a memory. You have two pointers pointing to the same place in a memory: ptr and node->left . Then you delete the memory and reset one of the pointers to NULL , but of course that does not make the other pointer to be reset too.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM