项目名称.exe 已触发断点

ProjectName.exe has triggered a breakpoint

本文关键字:断点 exe 项目      更新时间:2023-10-16

当运行程序时,它会正常运行,但总是抛出此错误。 它说错误来自以下行:

int* temp = new int[length];

我不知道为什么会这样。 程序按升序排序返回数组,但随后抛出断点。

void mergeSort(int *a, int low, int high)
{
if (low == high)
return;
int q = (low + high) / 2;
mergeSort(a, low, q);
mergeSort(a, q + 1, high);
merge(a, low, q, high);
}
void merge(int *a, int low, int q, int high)
{
const int length = high - low + 1;
int* temp = new int[length];
int i = low;
int k = low;
int j = q + 1;
while (i <= q && j <= high)
{
if (a[i] <= a[j])
temp[k++] = a[i++];
else
temp[k++] = a[j++];
}
while (i <= q)
temp[k++] = a[i++];
while (j <= high)
temp[k++] = a[j++];
for (i = low; i <= high; i++)
a[i] = temp[i];
}

我认为这是temp的内存访问违规

int k = low;

void mergek变量是数组索引temp。如果调用mergeSort(a, q + 1, high)merge low参数q + 1并且k超出范围 0 ~ 长度。

如果k超出范围 0 ~ 长度。temp[k]发生访问冲突。
我还建议在merge函数中添加delete[] temp
这是我的代码

int _a[] = { 5, 1, 3, 4, 2 }; // Test array!
void merge(int *a, int low, int q, int high)
{
const int length = high - low + 1;
int* temp = new int[length];
int i = low;
int k = 0;   // I fixed it(low -> 0)
int j = q + 1;
while (i <= q && j <= high)
{
if (a[i] <= a[j])
temp[k++] = a[i++];
else
temp[k++] = a[j++];
}
while (i <= q)
temp[k++] = a[i++];
while (j <= high)
temp[k++] = a[j++];
for (i = low; i <= high; i++)
a[i] = temp[i];
delete[] temp; // Add Delete
}
int main()
{
mergeSort(_a, 0, 5);
return 0;
}