【发布时间】:2016-11-12 02:40:15
【问题描述】:
我正在尝试纠正内存泄漏,但无法弄清楚删除数组 [] 不起作用的原因。我尝试搜索其他帖子,但我被卡住了,所以我希望我能指出正确的方向。
我正在尝试重新分配内存,但是当我使用删除数组 [] 时,我一直在破坏代码。
以下是输出的示例以及我想要实现的目标: enter image description here
代码如下:
int main()
{
cout << endl << endl;
int* nArray = new int[arraySize];
cout << "After creating and allocating memory for nArray." << endl;
cout << " nArray address is <" << nArray << "> and contains the value " << hex << *nArray << dec << endl;
for (int i = 0; i < arraySize; i++)
{
nArray[i] = i*i;
}
cout << "After initializing nArray." << endl;
cout << " nArray address is <" << nArray << "> and contains the value " << hex << *nArray << dec << endl << endl;
for (int i = 0; i < arraySize; i++)
{
cout << " nArray[" << i << "] = " << nArray[i] << " at address <" << nArray+i << ">" << endl;
}
cout << endl << "Before reallocating memory for nArray." << endl;
cout << " nArray address is <" << nArray << "> and contains the value " << hex << *nArray << endl;
nArray = new int[arraySize + 2];
cout << dec << "After reallocating memory for nArray." << endl;
cout << " nArray address is <" << nArray << "> and contains the value " << hex << *nArray << dec << endl;
for (int i = 0; i < arraySize+2; i++)
{
nArray[i] = i*i;
}
return 0;
}
【问题讨论】:
-
您可能已经探索过这个选项,但我想检查一下,为什么不使用 std::vector
来完成上面的操作? -
您给我们看的代码中没有
delete。