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?

nathanesau
  • 1,681
  • 16
  • 27
  • Change the function signature to `void delete_node(Node *&node)` – Aykhan Hagverdili Sep 23 '19 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 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. – Aconcagua Sep 23 '19 at 17:43

1 Answers1

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.

R Sahu
  • 204,454
  • 14
  • 159
  • 270