ProjectName.exe已触发断点

时间:2019-10-23 08:23:29

标签: c++ visual-studio debugging compiler-errors

在运行程序时,它可以正常运行,但始终会引发此错误。它说错误来自以下行:

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];
}

1 个答案:

答案 0 :(得分:0)

我认为这是temp上的内存访问冲突

    int k = low;

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

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

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;
}