Pointer question

I am just learning all the nuances of using pointers and have run into a sticky problem.

I am building a binary search tree. I have allocated multiple nodes (using new) and successfully placed them in the tree. My problem arises when I try to delete one of them.

I have a function called find that locates the node and returns a pointer to it and saves that pointer in a variable on the stack called node. I then have a function that attempts to delete that node.

I understand that the node was allocated with new so I should use delete to get rid of it, but when I try to delete it using delete &node;, I get an error. I think the problem is because I am trying to delete it using the variable on the stack with was not allocated with new.

How can I delete the object in memory (that was allocated with new) but using a pointer variable that is on the stack? The original variable that was used with new is long gone in another function.

My code works just fine if I just delete node; but if I understand correctly that only deletes the node variable on the stack, not the object pointed to by the variable.

Thanks for any suggestions or corrections to my thinking.

riversr54

Last edited on
Don't say delete &node. Just say delete node. It deletes the object with the address that's stored in node. There is no way to "delete" something that's on the stack (in this case the pointer variable holding the node's address). Stack variables are "deleted" automatically when the function returns.
Last edited on
My code works just fine if I just delete node; but if I understand correctly that only deletes the node variable on the stack, not the object pointed to by the variable.

You misunderstand. delete ptr doesn't delete ptr, it deletes whatever ptr points to. So it's perfectly fine to say:
1
2
3
4
Node *p1, *p2;    // declare two pointers
p1 = new Node;    // create a new Node and point p1 to it.
p2 = p1;          // Point p2 to the same Node.
delete p2;        // delete the Node using p2. 

Just to clarify...

I guess I'm still confused, in what situation would I use delete &node; if any?
Last edited on
in what situation would I use delete &node; if any
Basically never. The only way I can think of even making it work would be if node was a reference to a variable allocated on the heap:
1
2
3
int *ip = new int;
int &ir(*ip);
delete &ir;


Just remember that delete ptr deletes the object that ptr points to.
Thanks for the help. I swear I read somewhere that using the & was the correct way to delete the object instead of the pointer itself.

Thanks again,
this worked for me:

int * p = new int;
delete &(p[0]);

but it is just a confusing way to write delete(p); it serves no purpose.
Topic archived. No new replies allowed.