2011-09-16 75 views
1

一切正常工作,直到索引19的最后一个值。实际上,所有的值都打印出来,而不是。一旦它打印出最终值&索引,它就会发生故障。我假设这是因为它试图访问第20个值。我将如何防止这种情况发生?For循环上的C++分段错误

主要文件代码:

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

头部代码:

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

这是一个非常奇怪的实现。在'getNextItem'中'index'初始化了哪里?为什么列表像穷人的矢量一样遍历? –

+0

另外,神奇数字19和20从哪里来? –

回答

1

你的current->info是外部空的检查。当current为空时,您无法访问其指针并导致段错误

+0

我应该在这里包含哪些其他特定的代码?头文件大约是7个打印页面,这就是为什么我没有发布这一切。 到目前为止我改变的唯一的东西是在这个函数的底部: ** if(current == NULL) return 0; 其他 返回电流 - >信息; ** 另外,我试图保持它作为VAL-1,因此,它没有得到过在空点,但刚刚离开它缺少列表中的一个元素(最后一个)。 – jenna

+0

使用-1仍然不安全(它引用无效地址)。这取决于你希望返回什么(你的逻辑)告诉消费者什么时候没有更多的物品要退货。 – datalost

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

分配currentcurrent->next。当它是null然后你试图返回current->infocurrent是... null。

至少这是我的怀疑;你发布的代码是不完整的,并且不可能给你一个具体的答案......但是这肯定是一个罪魁祸首。