【问题标题】:Red Black Tree Insert Issues C++红黑树插入问题 C++
【发布时间】:2013-06-12 22:05:41
【问题描述】:

我目前正在执行一项任务,我要实现一个简单版本的红黑树。我目前在 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;
}

这是我的主要功能

int main(){


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

}

【问题讨论】:

  • 为什么要使用特殊的Nil 节点而不是nullptr(或0)?如果数据只是单个字符,为什么要使用一个数组并动态分配它,而您可以使用单个 char 而不是指针呢?
  • 你违反了Rule of Three 那里的纸杯蛋糕。你也在泄漏内存。

标签: c++ pointers exc-bad-access null red-black-tree


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    在 main 中,您只需在 RBT 中有一个指向树的指针,而无需对其进行初始化,然后调用未定义的行为区域。

    (而且代码还有很多其他可疑点)

    【讨论】:

    • 是的,那也是 :-o 在前半打之后,我认为不值得单独指出。
    猜你喜欢
    • 2011-08-06
    • 2012-12-01
    • 2018-11-06
    • 2013-11-17
    • 2011-01-19
    • 2011-08-03
    • 2013-05-02
    • 2021-06-27
    相关资源
    最近更新 更多