-2
#include <iostream>
using namespace std;
struct node{
  int val;
  node* left, *right;
};

void _delete(node *root)
{
  root = NULL;
}
void change(node *root)
{
  root->val = 6;
}
int main()
{
  node * root = new node;
  root->val = 5;
  change(root);
  _delete(root);
  cout<<root->val<<endl;
  return 0;
}

The output of the above program is 6. It seems as if the _delete function has no effect on the root node but change function has an effect on the root node. It is almost as if delete treats the argument passed as a local variable but change treats the argument as a global variable. Is there anything that I am missing out or is this normal? If it is normal, please explain.

canoodle
  • 13
  • 1
  • 4
  • "It seems as if the _delete function has no effect on the root node" It indeed does not. Why do you think it should? "change treats the argument as a global variable" no, it doesn't. It changes `root->val`. `root` is still local to it. – n. m. could be an AI Jul 06 '17 at 14:21
  • @Downvoters, this is clearly written with a compilable example. Please don't downvote on the grounds of obviousness. – Bathsheba Jul 06 '17 at 14:24
  • Your code also leaks memory, since it is not deallocating the object it allocated using operator `new`. Setting a pointer to some other value does not deallocate the object the pointer points to. And if `_delete` is supposed to set the pointer to `NULL` then you later dereference a `NULL` pointer in `cout<val< – jotik Jul 06 '17 at 14:25
  • You should use operator `delete` to delete the node's memory, then set the pointer to null. Otherwise, the program has the memory allocated but it's location will be lost and you won't be able to recover it, a.k.a. *memory leak*. – Thomas Matthews Jul 06 '17 at 16:12

1 Answers1

4

Since you pass the pointer by value in your _delete function, the value in the caller is not changed.

The quickest fix is to write

void _delete(node*& root)

i.e. pass the pointer by reference: note the &; you might also want to call delete on the pointer there too else you leak memory. The function change works as it is since you are using the pointer to member operator ->.

Bathsheba
  • 231,907
  • 34
  • 361
  • 483