Domanda

There are two sets of code that I think are equivalent, but one causes a seg fault and the other doesn't. I'm really confused about why this is the case...

What I would like is to create a find function that

This code does work:

    MyPair <Comparable, BinomialNode<Comparable>*> dummy(x, NULL);
    MyPair <Comparable, BinomialNode<Comparable>*>* pair = hashTable.find(dummy);
    if(pair!=NULL)
    {
        addDupe(x, pair);   
    }

void addDupe( Word & x, MyPair<Word, BinomialNode<Word>*>* pair)
{
    list<int>::iterator it;
    list<int> lines = x.getLineNums();
    for ( it=lines.begin(); it != lines.end(); it++ )
    {
        pair->second->element.addLineNum(*it);
    }
}

The code below does NOT work. The changes from the above is that I tried to do was to try to move the find function out and make it return a BinomialNode* which would be the second element in the MyPair. addDupe in this version handles BinomialNode* instead of MyPair*.

I tracked the segfault to return pair->second.
Why does that cause a segfault but pair->second->element.addLineNum(*it) from above does not?

BinomialNode<Comparable>* node = find(x);
if(node!=NULL)
{
    addDupe(x, node);
}

BinomialNode<Comparable>* find(Comparable& x)
{
    MyPair <Comparable, BinomialNode<Comparable>*> dummy(x, NULL);
    MyPair <Comparable, BinomialNode<Comparable>*>* pair = hashTable.find(dummy);
    if(pair!=NULL)
         return NULL;
     return pair->second; //LINE CAUSES SEGFAULT
}

void addDupe( Word & x, BinomialNode<Word>* node)
{
    list<int>::iterator it;
    list<int> lines = x.getLineNums();
    for ( it=lines.begin(); it != lines.end(); it++ )
    {
            node->element.addLineNum(*it);
    }
}
È stato utile?

Soluzione

if(pair!=NULL) //when pair is not 0
         return NULL;

so after that you trying to access to NULL pointer what is cause of SEGFAULT

You have to check for NULL:

if(pair==NULL) //when pair is 0
             return NULL;

Altri suggerimenti

if(pair!=NULL) return NULL;

should be if(pair==NULL) return NULL;

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top