I have a class
class Node {
public:
int value;
Node * next;
Node();
Node(const Node& other);
Node& operator= (const Node& other);
};
It’s not very useful, but it has an overridden assignment operator. Everything in there is public because I am such an open and cooperative guy.
Now elsewhere I have an array of these nodes:
Node * nodes = new Node[15];
When I try to assign a node to my array of nodes:
nodes[0] = Node();
I get a huge ugly crash.
My assignment operator looks like this:
Node& Node::operator= (const Node& other) {
// watch out for self assignment
if (this == &other) return *this;
delete this->next;
this->next = new Node(*(other.next)); // call the copy constructor
this->value = other.value;
return *this;
}
I get the feeling that I should be checking for whether or not this is NULL before I go about trying to dereference its members. Any thoughts on what might be wrong?
The problem is that you’re dereferencing
other.next, which might be NULL. So you should check ifother.nextis null before dereferencing it:Dereferencing a NULL pointer is undefined, so if you do it, anything might happen — it might NOT crash immediately and instead wander off into unexpected places, confusing both you and the debugger.