【发布时间】: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 = 0x7fff5fc01052 和data = 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