c++线程:EXC_BAD_ACCESS(代码=2,地址0x

c++ Thread: EXC_BAD_ACCESS(Code=2, address0x

本文关键字:0x 地址 代码 ACCESS 线程 EXC BAD c++      更新时间:2023-10-16

我正在尝试使用向量和模板的快速排序算法。我正在测试算法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个值)上一步一步地完成代码,以获得更好的理解。