红黑树插入问题

Red Black Tree Insert Issues C++

本文关键字:问题 插入      更新时间:2023-10-16

我目前正在完成一项任务,我要实现一个简单版本的红黑树。我目前在Xcode工作,它目前给我一个错误GDB: Program received signal: EXC_BAD_ACCESS…我认为这是内存泄漏…但我似乎找不到任何原因来解释为什么会发生这种情况。调试器显示我的问题是在我的RedBlackTree::treeInsert(char *data)函数....特别是与while循环体中的if语句if (strcmp(data, x->data) < 0)

调试器显示this = 0x7fff5fc01052data = 0x100001a61是存储字符(字母a)。然而,它显示x = 0x4810c48348ec8948,但它的所有属性(父,左,右,数据)都是空的。

所以我尝试的下一件事是确保我在node()构造函数中将这些变量初始化为Nil。但这给了我错误:'Nil' was not declared in this scope…所以我现在把它们注释掉了。不知道这里发生了什么?如有任何帮助,我将不胜感激。

class node
{
public:
char         *data;         // Data containing one character
node         *parent;       // pointer to this node's parent
node         *left;          // pointer to this node's left child
node         *right;          // pointer to this node's right child
bool         isRed;         // bool value to specify color of node
node();
};
node::node(){
this->data = new char[1];
isRed = true;
//this->parent = Nil;
//this->left = Nil;
//this->right = Nil;
}

红黑树类和方法

class RedBlackTree {
public: 
/*constructor*/
RedBlackTree();
node* getRoot(){
    return this->Root;
}
/*RB-INSERT*/
void rbInsert(char *data);
node treeInsert(char *data);
void rbInsertFixup(node *z);
/*ROTATE*/
void leftRotate(node *z);
void rightRotate(node *z);
/*INORDER TRAVERSAL*/
void inOrderPrint(node *root);

private:
node    *Root;    /*root*/
node    *Nil;    /*leaf*/
};

RedBlackTree::RedBlackTree() 
{
this->Nil = new node();
this->Root = Nil;
}
void RedBlackTree::rbInsert(char *data){
node z = treeInsert(data);
rbInsertFixup(&z);  
} // end rbInsert()
node RedBlackTree::treeInsert(char *data){
node *x;
node *y;
node *z;
y = Nil;
x = Root;
while (x!= Nil) {
    y = x;
    if (strcmp(data, x->data) < 0) {
        x = x->left;
    } else {
        x = x->right;
    }
}
z = new node(); // create a new node
z->data = data;
z->parent = y;
z->isRed = true; // set  new node as red 
z->left = Nil;
z->right = Nil;
if (y == Nil) {
    Root = z;
} else {
    if (strcmp(data, y->data)<= 0) {
        y->left = z;
    } else {
        y->right = z;
    }
}
return *z;
}

这是我的main函数

int main(){

RedBlackTree *RBT;
node* root = RBT->getRoot();
RBT->rbInsert((char *)"A");
RBT->inOrderPrint(root);
return 0;
}

到处都有缓冲区溢出!包含一个字符的字符串实际上是两个字符,因为它还有一个特殊的结束字符。您为数据分配单个字符的内存,但是您使用字符串会使这些缓冲区溢出。

在main中,你只是在RBT中有一个指向树的指针,而不初始化它,并调用未定义的行为区域。

(代码中有大量其他可疑点)