I recently updated my macbook to Sonoma 14.0 and am unable to run this program for a BST. It used to run just fine before I updated my laptop and now I'm getting a bus error. I'm fairly new at coding and don't know what to do to fix this. I would appreciate some help.
#include <iostream>
using namespace std;
template<typename Char> class BST {
public:
struct Node {
Char data;
Node* left;
Node* right;
};
Node* rootNode;
BST() {
rootNode->data = '\0';
rootNode->left = nullptr;
rootNode->right = nullptr;
}
Node* createNode(char ch) {
Node* nn = new Node;
nn->data = ch;
nn->left = nullptr;
nn->right = nullptr;
return nn;
}
void insert(char myChar) {
insertHelper(rootNode, myChar);
}
void inOrderTraversal() {
inOrderTraversalHelper(rootNode);
}
void preOrderTraversal() {
preOrderTraversalHelper(rootNode);
}
void postOrderTraversal() {
postOrderTraversalHelper(rootNode);
}
private:
char insertHelper(Node* &root, char ch) {
if (root->data == '\0') {
root->data = ch;
} else if ( ch < root->data) {
if (root -> left == nullptr) {
root -> left = createNode(ch);
} else {
insertHelper(root->left, ch);
}
} else {
if ( ch > root->data) {
if (root -> right == nullptr) {
root -> right = createNode(ch);
} else {
insertHelper(root->right, ch);
}
}
} return ch;
}
void inOrderTraversalHelper(Node* node) {
if (node != nullptr) {
inOrderTraversalHelper(node->left);
cout << node->data << " ";
inOrderTraversalHelper(node->right);
}
}
void preOrderTraversalHelper(Node* node) {
if (node != nullptr) {
cout << node->data << " ";
preOrderTraversalHelper(node->left);
preOrderTraversalHelper(node->right);
}
}
void postOrderTraversalHelper(Node* node) {
if (node != nullptr) {
postOrderTraversalHelper(node->left);
postOrderTraversalHelper(node->right);
cout << node->data << " ";
}
}
};
int main () {
BST<char> cisp_bst;
cisp_bst.insert('k');
cisp_bst.insert('e');
cisp_bst.insert('v');
cisp_bst.insert('b');
cisp_bst.insert('g');
cisp_bst.insert('p');
cisp_bst.insert('y');
cout << "\n" << "In order traversal: ";
cisp_bst.inOrderTraversal();
cout << "\n\n";
cout << "Post-order traversal: ";
cisp_bst.postOrderTraversal();
cout << "\n\n";
cout << "Pre-order traversal: ";
cisp_bst.preOrderTraversal();
cout << "\n\n";
return 0;
};
It ran just fine before but now it gives me a bus error. The debugger says it crashes in the first line of the constructor. (assigning data to '\0')
I try to debug with
lldbon my macbook(also Sonoma 14.0), and get the error message:EXC_BAD_ACCESSmeans that your program is trying to access memory that it doesn't have permission to access. And for your code, it happens in the constructor of yourBSTclass.So the solution is:
BST()fromTo:
if-statementof theinsertHelper()from:To:
This method works on my macbook, and I got this result:
Hope this also works for you.