Amaresh Amaresh - 2 months ago 15
C++ Question

having c-tor and d-tor gives segmentation fault while without them no segmentation fault

struct Tnode {
Tnode *left;
Tnode *right;
int content;

Tnode (int item = 0) {
this->content = item;
left = nullptr;
right = nullptr;
}};


class KrTree {
private:
Tnode* root;

void printHelper (Tnode* root) {
if(!root) {
return;
}
printHelper(root->left);
cout << root->content << " ";
printHelper(root->right);
}

void addHelper (Tnode *root, int item) {
if (root->content < item) {
if (root->right) {
addHelper(root->right, item);
} else {
root->right = new Tnode (item);
}

}else {
if (root->left) {
addHelper(root->left, item);
} else {
root->left = new Tnode (item);
}
}
}

public:
// KrTree (){
// }

void addTreeNode (int item) {
if (root){
this->addHelper(root, item);
} else {
root = new Tnode(item);
}
}

void tnodes_count () {

}

void deleteTreeNode () {

}

void printTree () {
printHelper (this->root);
}

//~KrTree (){}};


Above I've implented a binary search tree. please note i have commented my c-tor and d-tor. My problem is above code works good but give segmentation fault when i enable my c-tor and d-tor.

Here is client code:

KrTree* tree = new KrTree();
tree->printTree();
tree->addTreeNode(7);
tree->addTreeNode(2);
tree->addTreeNode(10);
tree->addTreeNode(1);
tree->addTreeNode(5);
tree->addTreeNode(9);
tree->addTreeNode(20);

tree->printTree();


I know that i am missing something very silly here. please let me know whey enabling my c-tor and d-tor gives segmentation fault

Answer

Without constructor KrTree.root is initialized by default 0 value. With constructor, well, it doesn't happen. Then addTreeNode tries to use this value as reference and segmentation fault happens. Default values in debug mode in Visual Studio are something like 0xcdcdcdcdcdcdcdcd. You can debug application up to first addTreeNode and see actual value for root. To fix this you should promptly initialize member variable value in constructor. For example:

KrTree () : root(nullptr) {
}
Comments