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

时间:2016-03-30 22:47:37

标签: c++ arrays memory dynamic

我收到此错误,"正常阻止"后检测到堆损坏。这是在阵列加倍并计算后#39;达到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;

}

1 个答案:

答案 0 :(得分:0)

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

然后,在count达到10之后,代码将经历使数组大小加倍的动作。

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