运行时的“分段错误”

时间:2013-09-15 06:57:00

标签: c++ segmentation-fault

void binarysearch(string key, vector<string>& f2){
sort_vector(f2);

int mid = 0;
int left = 0;
int right = f2.size();
bool found = false;
while (left < right){
    mid = left + (left+right)/2;
    if (key > f2[mid]){ 
        left = mid + 1;
    }
    else if(key < f2[mid]){
        right = mid;
    }
    else{
        found = true;
        left = right;
    }
}
cout << "out of while loop" << endl;
if (found == true){
    cout << "YES: " << key << endl;
}
else{
    cout << " NO: " << key << endl;
}
found = false;
}

当我运行它时,它会自动终止并显示“分段错误”而没有给出行号。这甚至意味着什么,为什么我得到这个错误?

提前致谢

1 个答案:

答案 0 :(得分:5)

分段错误意味着程序访问了无效的内存地址。我怀疑在这种情况下这是事实:

mid = left + (left+right)/2;

在某个时刻导致某个值大于正中值(因为它实际上与mid = 1.5 * left + 0.5 * right相同)。它应该是这样的:

mid = left + ( right - left ) / 2;

或者,更好的是(只要左右+的总和不超过MAXINT),正如mawia所暗示的那样:

mid = ( left + right ) / 2;