Hello,
I've got a decent grasp of basic C++, but pointers are still voodoo to me and I tend to avoid them. Considering they're a vital part of C programming, I decided to get some practice.
I've built a Binary Tree with basic functionality: A 'Node' class with a value (int), an lson and an rson(Node pointers), plus a 'Tree' class with a root (Node pointer). The 'Tree' class has an 'addNode(Node &n)'.
I've tested the Tree by manually making one as well as some Nodes, then manually adding them. That worked perfectly. Afterwards, I wanted to test it more thoroughly by means of adding a large amount of randomly generated values. The problem is I seemed to have messed up some of the 'pointering' and [probably not really] unexpected behaviour has occured.
The test function itself is simple:
1 2 3 4
|
for (int i = 0; i < n; ++i) {
Node temp = Node(rand()%5001);
t.addNode(temp);
}
|
Now, the problem is that the first node is assigned as the root ("root = &n;"), but that the address of 'n' is apparently reused every time a new node is generated. The result is that the value of the root Node is constantly overwritten.
I'm not certain how to fix this. Passing the Node to be added without the '&' would (to my understanding) lead to the root pointer pointing to a temporary copy of the Node, which is lost at the end of the function. Same thing if I make a new Node inside the Tree addNode() function.
How do I get around this, and what's the logic behind it?
P.S.: Secondary question: Imagine I were to dynamically create a variable (using new) and have it deleted later on. Then, I start the debugger, break somewhere between the new and delete, and then quit debugging. What happens to the memory allocation?