c++线程:EXC_BAD_ACCESS(代码=2,地址0x
c++ Thread: EXC_BAD_ACCESS(Code=2, address0x
我正在尝试使用向量和模板的快速排序算法。我正在测试算法100、1000和1M次。它可以进行一些测试,例如对随机列表进行排序,但当它对降序列表进行排序时,我在xcode中得到以下错误,并在终端中运行,我得到Segmentation错误:11。
Thread: EXC_BAD_ACCESS(Code=2, address0x...
我还是一个c++初学者,我不太明白我做错了什么。有什么建议或可能的解决方案吗?
#include <iostream>
#include <cstdlib>
#include <vector>
template <class T>
class quickSort {
public:
void sorting(std::vector<T>&);
void quick(std::vector<T>&, const unsigned&, const unsigned&);
unsigned counter;
};
template<class T>
void quickSort<T>::sorting(std::vector<T>& toSort)
{
unsigned max = 0;
max = (unsigned)(toSort.size()-1);
quick(toSort, 0, max);
}
template<class T>
void quickSort<T>::quick(std::vector<T>& toSort, const unsigned& leftarg, const unsigned& rightarg)
{
if (leftarg < rightarg) {
T pivotvalue = toSort[leftarg];
int left = leftarg - 1;
int right = rightarg + 1;
for(;;) {
counter++;
while (toSort[--right] > pivotvalue);
while (toSort[++left] < pivotvalue);
if (left >= right) break;
T temp = toSort[right];
toSort[right] = toSort[left];
toSort[left] = temp;
}
T pivot = right;
quick(toSort, leftarg, pivot);
quick(toSort, pivot + 1, rightarg);
}
}
leftarg是一个无符号的int。在第一次调用quick()时,它的值为0。如果从中减去一(int left = leftarg - 1
),则值溢出,得到UINT_MAX而不是-1。这会导致错误和分段错误,因为您使用left作为索引,并且UINT_MAX显然超出了有效的索引范围。
我建议您熟悉C++中的调试,并在一个小输入(比如5个值)上一步一步地完成代码,以获得更好的理解。
相关文章:
- 将数组的地址分配给变量并删除
- 空基优化子对象的地址
- C++ 指针的内存地址和指向数组的内存地址如何相同?
- 在C++中打印指向不同基元数据类型的指针的内存地址
- 如何在c++程序中找到函数的地址
- 向量元素的引用地址与它所指向的向量元素的地址不同.为什么
- 被解释为低级别const的const对象的地址
- 将地址分配给本地指针后,公共对象的变量将消失
- 为什么我在leetcode上收到AddressSanitizer:地址0x602000000058上的堆缓冲区溢出错误
- 内联程序集printf将整数解释为地址
- 为什么指针不写入类的地址?
- 如何在C++中获取该对象的类声明中对象的地址?
- 通过按地址访问变量
- 当一个新对象被分配到它的地址时,对象是否必须被销毁
- 函数名是c中该函数的第一条指令的地址吗
- Visual Studio(或任何其他工具)能否将地址解释为调用堆栈(boost上下文)的开头
- ReadProcessMemory() 不适用于像 0x2840C6C68D8 这样的长地址
- c++线程:EXC_BAD_ACCESS(代码=2,地址0x
- 为什么内存地址以0x开头
- 无法访问地址 0x 处的内存