-2

I apologize if this is too basic of a question or if it is common - I searched here as well as on Google with no luck.

I am trying to delete a node in a binary tree, but the delete operator seems to be doing nothing.

Here is my node:

struct node {

    node(int value) : left(NULL), right(NULL), quantity(1) { val = value; }

    int val;
    int quantity;
    node* left;
    node* right;

}

And my test code:

node* test = new node(15);
cout<<test<<'\n'; //Outputs memory address
cout<<test->val<<'\n'; //Outputs 15

delete test;
cout<<test<<'\n'; //Outputs same memory address
cout<<test->val<<'\n'; //Outputs 15

Any help is much appreciated! I peeked at the documentation and didn't see anything about bulk memory cleanups that would indicate to me it'll be cleared later.

apxcode
  • 7,696
  • 7
  • 30
  • 41
J S
  • 3,324
  • 4
  • 20
  • 27
  • 1
    Accessing the contents of what you just deleted is undefined behaviour. `delete` frees the memory just like it says, and if you had a logging destructor, you'd see output given the `delete` just executed and it being flushed. Whether the memory still has the old stuff in it isn't reliable in any way. – chris Aug 01 '14 at 20:47
  • 1
    All `delete` normally does is destroy the object and make the block of memory eligible for re-use, so some later call to `new` may receive that same address (or the address of a block that includes the same memory, anyway--might be a subset or superset of the same block). That doesn't mean the content necessarily disappears immediately (though it might). – Jerry Coffin Aug 01 '14 at 20:49
  • Read the answer to this question. It's basically the same thing. http://stackoverflow.com/questions/6441218/can-a-local-variables-memory-be-accessed-outside-its-scope – Marius Bancila Aug 01 '14 at 20:50
  • 3
    I didn't realize `new` and `delete` were added to C... – Drew McGowen Aug 01 '14 at 20:52
  • 1
    Maybe it's just me getting tired of people tagging questions as both C and C++ when it's clearly one or the other – Drew McGowen Aug 01 '14 at 20:53

1 Answers1

2

Deleting a node marks that space as available for reassignment. It does not clear it. The old value would remain there until it's reassigned and its new owner writes to it.

Writing to memory after it's been freed is undefined behaviour — which means anything can happen, with "anything" including "nothing out of the ordinary".

If you were to change that to:

delete test;
node* test2 = new node(55);
cout<<test<<'\n'; //Outputs same memory address
cout<<test->val<<'\n'; //Outputs 15

then you'd see something different.

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
James Curran
  • 101,701
  • 37
  • 181
  • 258