简体   繁体   English

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

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

I implemented a red black tree but when I run the program from the terminal, it gives the error: Segmentation fault core dumped. 我实现了一棵红黑树,但是当我从终端运行程序时,它给出了错误:分段故障核心已转储。 I think that I 'm accessing a location that I shouldn't be accessing or I'm accessing something null. 我认为我正在访问一个本不应该访问的位置,或者正在访问空值。

This is my insert method: 这是我的插入方法:

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);
}

This is part of my main: 这是我主要的一部分:

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

RedBlackTree<int, int> tree1;


    tree1.Insert(tree1, &q);

Can anyone help please? 有人可以帮忙吗? I am new to templates and I would really appreciate if someone helps me. 我是模板的新手,如果有人帮助我,我将不胜感激。

Thanks in advance. 提前致谢。

You are dereferencing the NULL-pointer (twice!): 您正在取消引用NULL指针(两次!):

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

I have a feeling you wanted to write: 我有种想写的感觉:

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

or 要么

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

Although both would be redundant, because you already have the pointer in this (but you can access the member variables directly anyway) and you already have the object Tree whose members you can access via Tree. 虽然这两个是多余的,因为你已经在指针this (但你可以直接访问反正成员变量),你已经有对象Tree ,其成员就可以通过访问Tree. , too (as long as they are public ). 也一样(只要它们是public )。

Also why do you pass a copy of the object to a method of itself? 另外,为什么还要将对象的副本传递给自身的方法呢? This is completely unnecessary. 这完全没有必要。 Even a reference would be redundant. 即使参考也将是多余的。

You probably should remove the Tree parameter, remove the line Node <Item, Key> *T=0; 您可能应该删除Tree参数,删除行Node <Item, Key> *T=0; and remove all T-> . 并删除所有T->

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

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