我正在进行一项任务,我将实施一个简单版本的红黑树。我目前正在使用Xcode,它目前正在给我一个错误GDB: Program received signal: EXC_BAD_ACCESS
...我假设它是一个内存泄漏...但我似乎无法发现任何原因,为什么会发生这种情况。调试器向我展示了问题在于我的RedBlackTree::treeInsert(char *data)
函数....特别是在while循环体if (strcmp(data, x->data) < 0)
中的if语句。
调试器显示存储char(字母A)的this = 0x7fff5fc01052
和data = 0x100001a61
。但是它显示x = 0x4810c48348ec8948
,但它的所有属性(父,左,右,数据)都是空的。
所以我接下来要做的就是确保在我的Nil
构造函数中将这些变量初始化为node()
。但是这给了我错误:'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;
}
答案 0 :(得分:1)
你到处都有缓冲区溢出!包含一个字符的字符串实际上是两个字符,因为它也有一个特殊的终止字符。您为数据的单个字符分配内存,但是使用字符串会使这些缓冲区溢出。
答案 1 :(得分:0)
在main中你只需要在RBT中指向树而不启动它,然后调用未定义的行为域。
(而且代码还有很多其他可疑点)