Insert function for a Binary Search Tree

Hi all,
I'm using recursive functions to insert a node into my binary search tree. The program works by creating a root node if there is none. Root is a pointer to a node object. If the root already exists I call the worker function.

Note: Key is int and Item is a string.

When calling the worker function, current->key(-858993460) and current->item(<Error reading characters of string.>) are not their expected values (1, "Harrold").

Recursion continues until this Exception occurs "Exception thrown: read access violation. current was 0xCCCCCCCC."

Key k and Item i are their expected value. It is only why I'm trying to access them from Node* root that they change and I'm unsure why this is happening.

Any help is appreciated



1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
void BST::insert(Key k, Item i)
{
	if (root == nullptr) {
		root = &Node(k, i);
	}
	else insertRec(k, i, root);
}

void BST::insertRec(Key k, Item i, Node* current)
{
	
	if (current->key == k)//if the key of the inserted node is = to an existing key, change the item.
	{
		current->item = i;
	}
	else if (current->key > k)//if the key of the current node is larger than key inserted traverse leftchild recursively calling function
	{
		if (current->leftChild != nullptr)
			insertRec(k, i, current->leftChild);
		else
			current->leftChild = &Node(k, i);
	}
	else if (current->key < k)
	{
		if (current->rightChild != nullptr)
			insertRec(k, i, current->rightChild);
		else
			current->rightChild = &Node(k, i);
	}
}
Last edited on
What do you do on line 4? A compiler does not accept that, because:
error: taking address of temporary


I'll hack around that in my example:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <iostream>

struct Foo {
    ~Foo() {
        std::cout << "I am DEAD DEAD DEAD\n";
    }
};

Foo * snafu() {
    Foo fubar;
    Foo * gaz = &fubar;
    std::cout << "SNAFU  " << gaz << '\n';
    return gaz;
}

int main()
{
    Foo * bar = nullptr;
    std::cout << "Before " << bar << '\n';
    bar = snafu();
    std::cout << "After  " << bar << '\n';
    std::cout << "Do I feel lucky?\n";
}

Before 0
SNAFU  0x78e2ebea41ae
I am DEAD DEAD DEAD
After  0x78e2ebea41ae
Do I feel lucky?

Well, do you?
Do you feel so lucky that you can dereference pointer bar in main() after the pointed to object has already been destructed?

Reread the material amout lifetime of objects.
Lifetime of automatic variables (in stack).
Lifetime of dynamically allocated objects (in free store).
Last edited on
Topic archived. No new replies allowed.