1

Everything works fine right up until the last value of index 19. In fact, all values are printed and what not. Once it prints the final value & index, it seg faults. I am assuming this is because it is trying to access the 20th value. How would I prevent this from occurring?

MAIN FILE CODE:

int index = 0;
while (index < list.length())
{
  cout << list.getNextItem(index) << " " << index << "\n";
  index++;
}

HEADER CODE:

template <class Type>
Type doublyLinkedList<Type>::getNextItem(const Type& val) const
{
    nodeType<Type> *current; //pointer to traverse the list

    current = first;  //set current to point to the first node

    for (index=0; index < val; index++)
    {
        if (current != NULL)
        {
            current = current->next;
        }
    }
    return current->info;
}//end getNextItem
2
  • 1
    That's a very weird implementation. In getNextItem Where is index initialized? Why is the list traversed like a poor man's vector? Commented Sep 16, 2011 at 3:04
  • Also, where did the magic numbers 19 and 20 come from? Commented Sep 16, 2011 at 3:06

2 Answers 2

3
for (index=0; index < val; index++)
{
    if (current != NULL)
    {
        current = current->next;
    }
}
return current->info;

You assign current to current->next. When it's null then you to try to return current->info when current is ... null.

At least that's my suspicion; the code you post is incomplete and it's impossible to give you a concrete answer ... but that certainly looks like a culprit.

Sign up to request clarification or add additional context in comments.

Comments

1

Your current->info is outside null checking. When current is null, you can't access its pointer and cause seg fault

2 Comments

What other specific code should I include here? The header file is about 7 printed pages which is why I didn't post that all. The only thing I changed so far was at the bottom of this function: if(current == NULL) return 0; else return current->info; Also, I tried keeping it as val-1, so that it didn't ever get to point at NULL, but that just left it missing one element in the list (last one).
Using -1 still not safe (It reference to invalid address). It depends on what you are expecting to return (your logic) to tell the consumer when there is no more Item to be returned.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.