检测到堆损坏(动态阵列重新调整大小)
Heap corruption detected (Dynamic array re-sizing)
我收到这个错误,"在正常块之后检测到堆损坏"。这是在数组加倍并且"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个位置。
相关文章:
- 为char数组调整zlib-zpipe
- 调整大小后指向元素值的指针unordered_map有效?
- 在C++中调整向量中的索引
- 哪些库可以通过Opencv调整曝光率
- 如何调整 std::vector of Eigen::MatrixXd 的大小
- Alt+Enter 在 Win32 应用中,管理大小调整和分辨率
- 在容量内调整矢量大小时的性能影响
- 将 boost::odeint 与向量类一起使用,而无需调整向量的大小
- 将摄像机调整到俯视图
- Qt 图表条形图调整大小崩溃
- 除非重新绘制大小,否则SDL_Texture在调整大小后呈现黑色
- 调整布局上的 QGraphicsView 小部件的大小
- 如何在构建链接列表时调整头、尾指针
- 如何将旧的 C 样式 #define 映射与现代C++进行调整?
- 使用大小调整大小调整 wxListView 的大小
- 通过新的后传递后创建的动态数组的错误以调整函数
- 我的数组大小调整代码在新数据上引发异常[size_t]
- OPENCV C 调整大小函数:新宽度应乘以3
- 在调整大小的动态数组中填充新元素
- 如何重新分配/调整3d数组的大小以适应新的大小