繁体   English   中英

在ubuntu上使用C ++进行分段错误(核心已转储)

[英]Segmentation fault(core dumped) with C++ on ubuntu

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

这是我的插入方法:

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->

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM