检测到堆损坏(动态阵列重新调整大小)

Heap corruption detected (Dynamic array re-sizing)

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

我收到这个错误,"在正常块之后检测到堆损坏"。这是在数组加倍并且"count"达到10之后。我做错了什么?谢谢,

int* temp = NULL; // temp defined likewise
int size = 10;
int count = 0;    // track array length
bool end = false; // flag to terminate while loop; AVOID using break stmt in loop
int* Arr = new int [size];  // Arr is pointer to an array of ints in heap
cout << endl;   // provide blank line so user sees first prompt easily
while (!cin.eof() && cin.good() && end == false)
{
    temp = new(int[10]);  // ask for one new int in heap
    if (temp != NULL)
    {  // if heap available
        cout << "Please enter an int number or EOF to terminate" << endl;
        cin >> *(temp + count);  // get user's next input
        if (!cin.eof() && cin.good())
        {  // if valid input
            for (int i = 0; i < count; i++) // enter Arr array into temp array
                *(temp + i) = *(Arr + i);
            delete[] Arr; // delete current reference in Arr
            Arr = temp;   // assign reference in temp to Arr
        }
        else
        {  // if user entered an invalid value including EOF in input
            if (!cin.eof())
            {
                cout << "Invalid Input" << endl;
            }
            end = true; // set flag to terminate while loop
        }
        count++;  // increment count of inputs for anticipated next input
        if (count == 10)
        {
            cout << "etsdgsdggd";
            int  newSize = size * 2;
            int* newArr = new int[newSize];
            for (int i = 0; i < count; i++)
                *(newArr + i) = *(Arr + i);
            size = newSize;
            delete[] Arr;
            Arr = newArr;
        }
    }
    else 
    {
        cout << "Heap exhausted." << endl;
        end = true;  // set flag to terminate while loop here also
    }
}
count--;  // decrement count, which was incremented in anticipation of
          //  another valid input
if (count > 0)
{  // if positive count, display entries of input array
    cout << "Input Array is: " << endl;
    for (int j = 0; j < count; j++) // display array
        cout << *(Arr + j) << " ";
    cout << endl;  // return cursor to lefthand position
}
//  system("PAUSE"); // in case your system expects PAUSE before ending program
return 0;

}

这是因为,由于某些不清楚的原因,此代码在循环的每次迭代中分配一个由十个整数组成的数组。然后将下一个值保存到数组的一个元素中,完全丢弃之前分配的数组和所有之前输入的值。

然后,在count达到10之后,代码经历阵列大小加倍的运动。

紧接着,在下一次迭代中,代码会分配另一个十元素数组,然后尝试将下一个数字保存到十元素数组的第11个位置。