c++ - ProjectName.exe已触发断点

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

最佳答案

我认为这是对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;
}

关于c++ - ProjectName.exe已触发断点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58518541/

相关文章:

c++ - 基于范围的 for 循环会抛出带有数组参数的编译器错误

Angular 2 : How enable debugging in angular2 from browser console

debugging - 延迟启动VS Code中的化合物调试

c++ - C++:迭代器的复制构造函数

C++ 在 Vector 类中调用私有(private)数据成员

html - 文件 > 新 MVC 3 项目上的新 "use HTML5 semantic markup"选项

c# - Visual Studio 停止运行我的程序

java - 如何调试部署在虚拟盒中的应用程序和主机操作系统中的源代码

c++ - 如何发送由 ON_NOTIFY 处理的通知?

c++ - crtp 和类型可见性