由于阵列使用,检测到堆损坏

Heap corruption detected due to array usage

本文关键字:检测 损坏 于阵列 阵列      更新时间:2023-10-16

对不起,我是C++和编程的新手,遇到了堆损坏错误。我想我是在未分配的内存中写的,但我似乎找不到错误在哪里……程序很容易接受用户输入值,并重新排列它们,使它们上升。我也在学习模板。

#include <iostream>
#include <iomanip>
#include <cmath>
using namespace std;
template <typename T>
void sort(T arrayz[], int size, char ch)
{
    T temporary;
    int k, j;
    if (ch = 'a')
    {
        for (k = 0; k < size; k++)
        {
            for (j = 0; j < size; j++)
            {
                temporary = arrayz[j];
                arrayz[j] = arrayz[j + 1];
                arrayz[j + 1] = temporary;
            }
        }
    }
}
int main()
{
    int choices, range, i;
    int x;
    char ch;
    cout << ("Enter the amount of numbers you want =>");
    cin >> x;
    int *numbers = new int[x];
    if (!numbers)
    {
        cout << "Memory Allocation error!";
        cin.get();
        exit(1);
    }
    for (int i = 0; i<x; i++)
    {
        cout << "Option number" << i + 1 << " =>";
        cin >> numbers[i];
    }
    cout << "Do you want ascending or descending values (a/d) =>" ;
    cin >> ch;
    if (ch = 'a')
    {
        sort(numbers, x, ch);
    }
    else if (ch = 'd')
    {
        sort(numbers, x, ch);
    }
    delete[] numbers;
    fflush(stdin);
    cin.get();
    return 0;
}

sort函数中,您正在访问索引为j + 1的元素。然而,这是越界的。arrayz数组的有效索引为0size-1。当jsize-1时,j+1size,其访问经过阵列的末尾。