Nie wiem co mogłoby być przyczyną, ponieważ get_root() nie robi problemów, a display() bez problemu iteruje po drzewie i odczytuje wszystkie dane z węzłów.
The thread 0x4cc8 has exited with code 0 (0x0).
Exception thrown at 0x005A109A in BST.exe: 0xC0000005: Access violation reading location 0x0000000C.
main.cpp
#include "bst.h"
#include <iostream>
#include <time.h>
using namespace std;
int num() {
return rand() % 100;
}
int main()
{
srand(time(NULL));
int size = 4;
Bst<int>* drzewo = new Bst<int>();
for (int i = 1; i < size; i++){
drzewo->add_new(num());
}
drzewo->add_new(15);
cout << (&drzewo->get_root())->data;
drzewo->display();
cout << (drzewo->search(&drzewo->get_root(), 15))->data << endl; // tutaj wyrzuca wyjątek
delete drzewo;
return 0;
}
bst.h
#include <time.h>
#include <iostream>
template <class T>
class Bst {
struct Node {
Node(T value) : data(value) {}
Node* parent = nullptr;
Node* left = nullptr;
Node* right = nullptr;
T data;
int index = 1;
int depth = 0;
};
unsigned int size = 0;
unsigned int height = 0;
unsigned int deepest_nodes_counter = 1;
Node* root = nullptr;
unsigned int last_index = 1;
public:
void add_new(T value) {
Node* temp = new Node(value);
temp->index = last_index++;
if (!root) {
root = temp;
size++;
}
else {
auto current = root;
for (unsigned int i = 1; true; i++) {
auto last = current;
if (value == current->data) {
temp->parent = current;
if (current->left) {
temp->left = current->left;
}
current->left = temp;
temp->depth = i;
if (i > height) {
height = i;
deepest_nodes_counter = 1;
}
else if (i == height)
deepest_nodes_counter++;
size++;
break;
}
current = (value < current->data) ? current->left : current->right;
if (!current) {
temp->parent = last;
if (value < last->data)
last->left = temp;
if (value > last->data)
last->right = temp;
temp->depth = i;
if (i > height) {
height = i;
deepest_nodes_counter = 1;
}
else if (i == height)
deepest_nodes_counter++;
size++;
break;
}
}
}
}
//pre-order search
Node* search(Node* node, T value) {
auto current = root;
if (current->data == value) {
return current;
}
else {
search(current->left, value);
search(current->right, value);
return nullptr;
}
}
};
całość kodu: https://godbolt.org/z/xe81zh