Hi i'm writing some functions for a heap represented as a tree. My Node is a struct:
template<typename Object>
struct Node
{
Node * parent = nullptr;
Object name;
Node * left = nullptr;
Node * right = nullptr;
Node(Object n) : name(n){}
};
And my class has a private variable called root, which is the root of the tree. Here are the functions that cause an issue, specifically insert_spot:
template<typename Object>
void MyPriorityQueue<Object>::insert(const Object & elem)
{
Node<Object> n_node = Node(elem);
Node<Object> * new_node = &n_node;
if (cur_amount > level_amount)
{
cur_amount = 1;
level += 1;
level_amount += level_amount;
}
if (root == nullptr)
{
root = new_node;
cur_amount += 1;
cur_size += 1;
if (cur_amount > level_amount)
{
cur_amount = 1;
level += 1;
level_amount += level_amount;
}
return;
}
insert_spot(new_node); //insert node at bottom
}
And insert_spot is:
void insert_spot(Node<Object> * new_node)
{
Node<Object> * parent_node = root;
unsigned temp_amount = cur_amount;
while (temp_amount > 2)
{
temp_amount -= temp_lvl_amount;
}
if(temp_amount == 1)
{
parent_node->left = new_node;
}
else{parent_node->right = new_node;}
new_node->parent = parent_node;
cur_amount += 1;
cur_size += 1;
}
I know what the issue is, in the insert_spot function, when I try to do parent_node->left = new_node, or parent_node->right = new_node, a segmentation fault is given. 1If I substitute it with (and say Object type is int)
Node<Object> n_node = Node(5)
parent_node->left = &n_node;
same thing with parent_node->right, then it works fine.
My previous code worked, using the 'new' operator to create pointers, but I can't use that here because of some later obstacles.
I figure that the issue is with 'const Object & elem' somehow, but I can't really figure out why I can't do parent_node->left = new_node or parent_node->right = new_node.
Also just an example input from main:
MyPriorityQueue<int> test;
test.insert(5);
test.insert(4);
I'm not looking for a specific answer, just trying to understand why parent_node-> causes a segmentation fault.