#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->leftobject ie. thenew 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:
Or this
Here is an improved depiction I made to show what I’m saying:
