3

I have a simple question.

Consider the code below:

#include <iostream>

struct Node {
    int data;
    Node *left;
    Node *right;
    Node(int pData) : data(pData), left(nullptr), right(nullptr) {}
};

void delete_node(Node *node) {
    delete node;
    node = nullptr;
}

int main() {
    Node *node1 = new Node(1);
    Node *node2 = new Node(2);
    delete_node(node1);
    delete node2;
    node2 = nullptr;
    if (node1) std::cout << "node1: " << node1->data << std::endl;
    if (node2) std::cout << "node2: " << node2->data << std::endl;
    return 0;
}

Which produces the output:

node1: -572662307

Which I find odd since I set node1 = nullptr in function delete_node. Can someone please explain?

2
  • Change the function signature to void delete_node(Node *&node) Commented Sep 23, 2019 at 16:55
  • One thing I'd like to add (the duplicate doesn't address): You won't get into the same trouble with std::unique_ptr: void destroy(std::unique_ptr<whatEver> object). Unique pointers cannot be copied, so you are forced to move them: std::unique_ptr<...> p; destroy(std::move(p)); leaving the outer pointer at empty state (even before the function call). Additional advantage: Self-documenting code. Already the function signature shows that the function will take ownership of the object. Commented Sep 23, 2019 at 17:43

1 Answer 1

7

The line

node = nullptr;

changes the value of the function local variable. It does not change the value of node1 in the calling function.

Change the function to accept its argument by reference.

// node is a reference to the pointer
void delete_node(Node*& node) {
    delete node;
    node = nullptr;
}

PS

Your program has undefined behavior. The value of node1 is not nullptr in main but the object that it points to has been deleted. Dereferencing the pointer and accessing its member variable is undefined behavior.

Sign up to request clarification or add additional context in comments.

2 Comments

OK thanks, I feel stupid now :P
@nathanesau, don't feel too bad. Most of us have been through such errors :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.