【发布时间】:2014-08-01 01:01:35
【问题描述】:
以下代码会引发错误。错误在 delete[] pIntArray 错误是 _ASSERTE(_BLOCK_TYPE_IS_VALID(pHead->nBlockUse));:
#include <iostream>
using std::cout;
using std::endl;
int main()
{
int* pIntArray = new int[50];
cout << "adding numbers to array ..." << endl;
for (int i = 0; i < 50; i++)
{
pIntArray[i] = i + 10;
}
cout << "values in array: " << endl;
for (int i = 0; i < 50; ++i)
{
cout << "integer[" << i << "] = " << *(pIntArray++) << endl;
}
cout << "deleting dynamic memory ..." << endl;
delete[] pIntArray;
cout << "memory deleted." << endl;
return 0;
}
但事实并非如此。唯一的区别是我正在复制指针并递增副本:
#include <iostream>
using std::cout;
using std::endl;
int main()
{
int* pIntArray = new int[50];
cout << "adding numbers to array ..." << endl;
int* pCopy = pIntArray;
for (int i = 0; i < 50; i++)
{
pIntArray[i] = i + 10;
}
cout << "values in array: " << endl;
for (int i = 0; i < 50; ++i)
{
cout << "integer[" << i << "] = " << *(pCopy++) << endl;
}
cout << "deleting dynamic memory ..." << endl;
delete[] pIntArray;
cout << "memory deleted." << endl;
return 0;
}
有人能解释一下原因吗?提前致谢。
【问题讨论】:
-
你给
delete[]的指针必须与你从new[]得到的指针相匹配。在这种情况下,您在两者之间增加了它。这也适用于普通的new/delete和malloc/free。你的第二个例子是正确的。