user3452239
user3452239

Reputation: 13

C++ working with pointers

I don't understand why it outputs "123" even though the deletenode function set x to NULL.

#include <iostream>;
using namespace std;
struct node {int value; struct node *left,*right,*parent;};
void deletenode(node *a) {
    delete a;
    a=NULL;
}
int main(int argc, const char * argv[])
{
    node *x = new node;
    x->value=123;
    deletenode(x);
    if (x!=NULL) cout << x->value;
}

Upvotes: 1

Views: 145

Answers (5)

Hal Canary
Hal Canary

Reputation: 2250

#include <iostream>

template<typename T>
void destroy(T*& ptr) {
  delete ptr;
  ptr = NULL;
}

template<typename T>
struct node {
  node(T t) : value(t) { }
  ~node() {
    delete left;
    delete right;
  }
  T value;
  struct node *left,*right,*parent;
};

int main(int argc, const char * argv[]) {
  node<int> *x = new node<int>(123);

  destroy(x);

  if (x != NULL) {
    std::cout << x->value << '\n';
  }
}

Upvotes: 0

Jimm
Jimm

Reputation: 31

Although you've successfully deleted the object you intended to, the pointer itself is passed by value (copied to variable 'a') to deletenode(). So even though variable 'a' inside the function is null, variable 'x' is still pointing to the now-deleted memory.

Upvotes: 1

Aleksei Petrenko
Aleksei Petrenko

Reputation: 7188

You pass this pointer to the function BY VALUE - this means you wont see changes outside of the function. Try to pass it by reference.

Upvotes: 0

Jack
Jack

Reputation: 1616

Because with delete you are actually marking the memory as free and ready to be reused, but the content of the area is probably left untouched

Upvotes: 0

Konrad Rudolph
Konrad Rudolph

Reputation: 546073

You have the following signature: void deletenode(node *a). You pass a pointer x to the function. The pointer value gets copied. Inside the function, you modify the local pointer value by writing to it via a = NULL.

However, that modification happens on the copy. The original remains unaffected. Notice that this isn’t true for delete, since delete doesn’t modify the pointer, it modifies (or rather, purges) the pointee.

The superficial solution is to pass the pointer value by reference:

void deletenode(node*& a)

However, there’s a consensus that setting pointers to nullptr (or NULL) after deletion doesn’t really help, and is therefore not normally done. I would therefore replace your whole call to deletenode with a simple delete x; statement.

Upvotes: 3

Related Questions