开发者

C++ Segmentation Fault on For Loop

开发者 https://www.devze.com 2023-04-05 19:08 出处:网络
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

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<Typ开发者_如何学运维e> *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


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.


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

0

精彩评论

暂无评论...
验证码 换一张
取 消