c++ - 未知错误,调试器只给我一个内存地址

标签 c++ debugging exception

我正在尝试制作一个简单的快速排序算法,但每当我运行它时,它都会抛出一个异常,我无法调试它。错误显示“Final.exe 中 0x00D01367 处的未处理异常:0xC0000005:访问冲突写入位置 0x00000000。”我不能使用 s[i] = value; 而应该使用 s.push_back(value); 吗?我以前使用前者没有任何问题,所以我不知道为什么我现在会收到错误。

#include <iostream>
#include <vector>
#include <list>
#include <cassert>
using namespace std;

typedef unsigned int uint;


uint partition(uint low, uint high, vector<double> & s)
{
uint i; //first index for partitioning
uint j; //second index for partitioning
uint pivotpoint; //index of the partition
double pivotvalue; //value at the pivot
double swapvalue; //placeholder variable for the swap

pivotvalue = s[low];
j = low;
for (i = (low+1); i<=high; i++)
{
    if (s[i] < pivotvalue)
    {
        j++;
        swapvalue = s[i];
        s[i] = s[j];
        s[j] = swapvalue;
    }
}
pivotpoint = j;
swapvalue = s[low];
s[low] = s[pivotpoint];
s[pivotpoint] = swapvalue;

return pivotpoint;
}

void quicksort(uint low, uint high, vector<double> & s)
{
uint pivotpoint;

if(high>low)
{
    pivotpoint = partition(low,high,s);

    if(pivotpoint != 0)
    {
        quicksort(low, pivotpoint-1, s);
    }
    if(pivotpoint != high)
    {
        quicksort(pivotpoint+1,high, s);
    }
}
}

int main( /*int argc, char* argv[] */)
{/*
  if( argc != 2 )
  {
cout << "Usage: ./filename.txt" << endl;
cout << "filename.txt should be a file with the items to be sorted" << endl;
exit( 2 );
  }
  assert(argc == 2)
  {
  }
  */
vector<double> s;
s[0] = 1.1;
s[1] = 2.4;
s[2] = 7.1;
s[3] = 5.4;
s[4] = 2.5;
s[5] = 1.2;
s[6] = 0.9;
quicksort(0,s.size(),s);
for(uint i = 0; i<s.size(); i++)
{cout << s[i] << endl;}
return 0;
}

最佳答案

一个直接的问题是你的 vector 初始化:

vector<double> s;
s[0] = 1.1;
s[1] = 2.4;
s[2] = 7.1;
s[3] = 5.4;
s[4] = 2.5;
s[5] = 1.2;
s[6] = 0.9;

所有上述 s[] 赋值都是越界的,因为 vector 的大小为零。

最简单的修复可能是将第一行更改为:

vector<double> s(7); // set the size at construction

在 C++11 中,您可以将整个内容替换为:

vector<double> s{1.1, 2.4, 7.1, 5.4, 2.5, 1.2, 0.9};

关于c++ - 未知错误,调试器只给我一个内存地址,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13751027/

相关文章:

C++ OOP 库存和项目类

c++ - Visual Studio 2012 中的 Visual C++ 使用 XAML

java - 替换 Arraylist 中的空值

c++ - 手动定义的 strlen 的奇怪行为

c++ - 是否可以在 C++ 中使用 DateTime 值?

javascript - 如何调试肉桂小程序?

eclipse - 是否可以将调试 session 附加到Eclipse CDT中正在运行的程序

C# 调试与发布

ruby-on-rails - Hoptoad v. Exceptional v. exception_notification v. exception_logger

c# - AutoMapper,尝试并捕获映射