红黑树插入问题
Red Black Tree Insert Issues C++
我目前正在完成一项任务,我要实现一个简单版本的红黑树。我目前在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;
}
这是我的main函数
int main(){
RedBlackTree *RBT;
node* root = RBT->getRoot();
RBT->rbInsert((char *)"A");
RBT->inOrderPrint(root);
return 0;
}
到处都有缓冲区溢出!包含一个字符的字符串实际上是两个字符,因为它还有一个特殊的结束字符。您为数据分配单个字符的内存,但是您使用字符串会使这些缓冲区溢出。
在main中,你只是在RBT中有一个指向树的指针,而不初始化它,并调用未定义的行为区域。
(代码中有大量其他可疑点)
相关文章:
- 屏幕插入运算符<<的运算符过载问题
- 我想直接在结构中插入,但没有一种方法可以正确避免填充问题
- 插入操作的二叉搜索树代码问题
- 当索引位于末尾和空数组时,向数组插入元素时出现问题
- 在链表中的某个点插入时出现问题,C++中的继承函数
- 通过C ODB插入汉字时的问题
- 在我的Quadtree中插入点问题
- 自己的C++列表类实现(插入函数)出现问题
- 单个链表,节点插入最低到最高节点值的问题
- BST插入的这段代码有什么问题?
- 在二叉搜索树中插入时出现问题
- 通过 ODBC C++将带有日期时间的记录插入 SQL Server 2014 的问题
- 二叉搜索树插入数据问题
- 我的二叉搜索树插入逻辑有什么问题?
- 测试外壳,插入和快速的程序问题
- 二叉搜索树在插入功能方面有问题
- 尝试在链表程序的末尾进行更简单的插入.小问题需要帮助
- 在二叉树中插入/查找问题
- 我的插入排序代码有问题
- 在将结构插入设置C++时遇到问题