Reputation: 115
Why checking the validity of root results in segmentation fault and what is the correct way of checking if the pointer is null?
class Node {
public:
int key, value;
std::shared_ptr<Node> right, left;
Node(int key, int value) : key(key), value(value) {
right = nullptr;
left = nullptr;
}
};
class BST {
private:
std::shared_ptr<Node> root = nullptr;
public:
void addElement(int key, int value) {
if (root) {
}
}
};
int main() {
std::shared_ptr<BST> bst;
bst->addElement(10, 10);
}
Upvotes: 1
Views: 678
Reputation: 229058
You forgot to create an instance of your BST class in main(),
bst->addElement(10, 10);
calls addElement
on a null pointer, that's where the segfault comes from. Instead do
auto bst = std::make_shared<BST>();
bst->addElement(10, 10);
Upvotes: 2