下面我有兩個函數,當insertItem調用findIndex時會產生分段錯誤。出於某種原因,返回值時會發生這種情況。 (我將包括cout語句,以便很容易地看到發生此錯誤的確切位置)。我試圖找到不在列表中的值的索引,因此-1應該被返回,但從來沒有。輸出如下。返回時的分段錯誤int
template <class ItemType>
int SortedList<ItemType>::findIndex(ItemType item) {
cout << "Entering findIndex function" << endl;
int first = 0;
int last = length-1;
int middle;
bool found = false;
while(!found) {
middle = (first+last)/2;
cout << "In findIndex, this is middle: " << middle << " and this is the item: " << item << " and this is the length: " << length << endl;
if(info[middle] == item) {
cout << "In findIndex found is now true" << endl;
found = true;
}
else if(item < info[middle])
last = middle-1;
else// if(item > info[middle])
first = middle+1;
if(first > last)//else// if(first > last)
break;
}
cout << "About to exit and return value from findIndex function" << endl;
if(found == true) {
cout << "findIndex Function: the index of the found value was " << middle << endl;
return middle;
}
else {
cout << "findindex Function: -1 was returned" << endl;
return -1;
}
}
template <class ItemType>
void SortedList<ItemType>::insertItem(ItemType item) {
cout << "Inside insertItem function, length: " << length << endl;
if(findIndex(item) != -1)
cout << "**Item already in the list" << endl;
else if(length == Max_Items)
cout << "**There is no room in the list" << endl;
else {
cout << "before the try" << endl;
try{
cout << "This is length at the start of the insertItem function: " << length << endl;
if(length == 0) {//if the list is empty item becomes the first item in the list \
cout << "This is right after length==0 in insertItem function" << endl;
info[0] = item;//was this->inf...
length++;
cout << "This is length right after incrementing it up" << length << endl;
}
else {//its not the first item in the list
for(int i = 0; i <= length; i++) {
cout << "This is the length and i respectively right inside the for in insertItem" << length << " " << i << endl;
if(i == length) {
cout << "this is where i == length" << endl;
info[i] = item;
length++;
break;
}
if(info[i] < item)
continue;
//inserting the item where it needs to go
for(int p = length; p > i; p--) {//was >=
info[p] = info[p-1];
}
//item = info[i];
info[i] = item;
length++;
break;
}
}
}catch(...) {cout << "**insertItem failed" << endl;}
}
cout << "This is length at the end of the insert item function: " << length << endl;
}
輸出: ... 內部insertItem功能,長度:0
輸入findIndex功能
在findIndex,這是中間位置:0,這是該項目:名稱:林二汶ID :81012,這是長度:0
從findIndex函數關於退出和返回值
findindex功能:-1返回
分割故障(核心轉儲)
〜$:
說着-1返回即使打印被擊中,但從來都沒有變回原來的功能。我不確定在這個區域會發生什麼可能導致seg故障。這個回報能做到嗎?
解決此類問題的正確工具是您的調試器。在*堆棧溢出問題之前,您應該逐行執行您的代碼。如需更多幫助,請閱讀[如何調試小程序(由Eric Lippert撰寫)](https://ericlippert.com/2014/03/05/how-to-debug-small-programs/)。至少,你應該[編輯]你的問題,以包含一個[Minimal,Complete,and Verifiable](http://stackoverflow.com/help/mcve)例子來重現你的問題,以及你在調試器中所做的觀察。 –
'findIndex'不處理空的容器。 – Rabbid76
嚴重的是,您使用的是模板,無法使用調試器來調試自己的代碼?這是一場災難。學習使用調試器,因爲它基本上是一項要求,因爲你正在做的事情具有先進性。 – PaulMcKenzie