std::nth_element函数越界访问导致 崩溃
代码实现
#include <iostream>
#include <algorithm>
bool TestCompa(int row1, int row 2)
{
return true;
}
int main()
{
std::vector test;
test.resize(123);
std::nth_element(test.begin(), test.begin() + 100, test.end(), TestCompa);
return 0;
}
以上代码固定崩溃
崩溃位置在 c++/11/bits/predefined_ops.h:158 (我使用的 是gcc 11.2.1 算比较新了 )
崩溃代码 {retrun bool(_M_comp(*__it1, *__it2));}
原因是: __it2指向的地址 是一个非法的,非预期的 是 test.begin() -1的 地址
造成这个崩溃的根本原因是因为: nth_element函数是严格弱序的
如果两个相等的值或大于 而比较函数 (TestCompa)返回了 true就会 崩溃
具体解释