删除数组时:"Process returned -1073740940 (0xC0000374)" 仅限某些数字

When deleting array: "Process returned -1073740940 (0xC0000374)" Only with certain numbers

程序returns用户N个从1开始的奇数方格

从数字 5-10 到 20,(我没有进一步)删除数组 A 时它崩溃并显示错误消息:“进程返回 -1073740940 (0xC0000374)”。哪一个显然是内存违规?

#include <iostream>
using namespace std;

int main(){
    int ok;
    int counter;
    do {
        int size;
        while (true) {
            cout << "Enter the number of perfect odd squares you want" << endl;
            cin >> size;
            if(size<1) {
                cout << "Enter a valid number" << endl;
                continue;
            }
            else break;
        }
        if (size%2==0) counter=size*2-1;
        else counter=size*2;
        int *A = new int[size];
        for (int i=1; i<=counter; i=i+2){
            A[i]=i*i;
            cout<<A[i] << endl;
        }
        delete[]A;

        cout << " Continue (1) or quit (0)?" << endl;
        cin >> ok;

    }while(ok==1);

}

来自NTSTATUS reference

0xC0000374 STATUS_HEAP_CORRUPTION - A heap has been corrupted

您似乎越界访问了 A(堆分配对象)- A[0]A[size-1] 是可以访问的有效元素,但 counter 高达2*size。任何试图写入超过 A[size-1] 的值都可能破坏导致此错误的堆。

先计算 counter 并将其用作分配大小。