2011-09-16 74 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。

至少這是我的懷疑;你發佈的代碼是不完整的,並且不可能給你一個具體的答案......但是這肯定是一個罪魁禍首。