在 ubuntu 上C++分段错误(核心转储)

Segmentation fault(core dumped) with C++ on ubuntu

本文关键字:核心 转储 错误 分段 ubuntu C++      更新时间:2023-10-16

我实现了一棵红色的黑色树,但是当我从终端运行程序时,它给出了错误:分段故障核心转储。我认为我正在访问一个我不应该访问的位置,或者我正在访问一些空的东西。

这是我的插入方法:

template <class Item, class Key>
void RedBlackTree<Item, Key>::Insert(RedBlackTree<Item,Key> Tree, Node<Item, Key> *z)
{
    Node <Item, Key> *T=0;
    Node<Item, Key>* nill=T->nill;
    Node<Item, Key>* root=T->root;
    Node<Item, Key> *y;
    Node<Item, Key> *x;
    y=nill;
    x=root;
    //x= T->getRoot();
    while(x != nill)
    {
        y=x;
         if(z->getKey() < x->getKey())
             x= x->getLeft();
         else
             x = x->getRight();
    }
    z->setParent(y);
    if(y == nill)
        z=T->root;
    else
    if((z->getKey())<(y->getKey()))
    {
        y->setLeft(z);
    }
    else
    {
        y->setRight(z);
    }
        z->setLeft(nill);
        z->setRight(nill);
        z->colour1 = 'R';
        FixingInsert(Tree,z);
}

这是我的主要内容的一部分:

Node<int, int> q = Node<int, int>(0,5);
RedBlackTree<int, int> tree1;

    tree1.Insert(tree1, &q);

谁能帮忙?我是模板的新手,如果有人帮助我,我将不胜感激。

提前谢谢。

您正在取消引用 NULL 指针(两次!

Node <Item, Key> *T=0;
Node<Item, Key>* nill=T->nill;
Node<Item, Key>* root=T->root;

我有一种感觉,你想写:

RedBlackTree <Item, Key> *T= &Tree;
Node<Item, Key>* nill=T->nill;
Node<Item, Key>* root=T->root;

RedBlackTree <Item, Key> *T= this;
Node<Item, Key>* nill=T->nill;
Node<Item, Key>* root=T->root;

尽管两者都是多余的,因为您已经在this中拥有指针(但无论如何您都可以直接访问成员变量),并且您已经拥有对象Tree,您也可以通过 Tree. 访问其成员(只要它们是public)。

另外,为什么要将对象的副本传递给自身的方法?这是完全没有必要的。即使是引用也是多余的。

您可能应该删除Tree参数,删除行Node <Item, Key> *T=0;并删除所有T->