【问题标题】:When deleting array: "Process returned -1073740940 (0xC0000374)" Only with certain numbers删除数组时:“进程返回-1073740940(0xC0000374)”仅具有某些数字
【发布时间】:2022-01-04 02:53:20
【问题描述】:

程序返回用户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);

}

【问题讨论】:

  • 如果您的计数器是数组大小的两倍,那么当您超出范围时,您希望在for 循环中发生什么?
  • counter 大于 size。您分配一个包含size 元素的数组,但访问的索引最高可达counter,包括counter;因此您的程序表现出未定义的行为。

标签: c++ arrays codeblocks dynamic-arrays


【解决方案1】:

来自NTSTATUS reference

0xC0000374 STATUS_HEAP_CORRUPTION - 堆已损坏

您似乎越界访问A(堆分配的对象)-A[0]A[size-1] 是可以访问的有效元素,但counter2*size 一样高。任何尝试写入超过 A[size-1] 的值都可能会损坏堆,从而导致此错误。

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

【讨论】:

  • 好的,谢谢。我应该注意到这么简单的错误,但不知怎的我没有。
猜你喜欢
  • 2020-09-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-11-25
  • 2023-01-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多