在同一个指针上调用new []两次而不调用delete []会导致内存泄漏? [英] Does calling new [] twice on the same pointer without calling delete [] in between cause a memory leak?
问题描述
我听说你应该通常删除,当你使用新,但当我运行一个简单的测试程序(下面),它似乎没有什么影响我放在arraySize或numLoops 。这是否会导致内存泄漏?
I've heard that you should usually "delete" whenever you use "new", yet when I run a simple test program (below), it doesn't seem to make a difference which numbers I put for arraySize or numLoops. Does this cause a memory leak?
#include <iostream>
int main()
{
double *array;
const int arraySize = 100000;
const int numLoops = 100000;
for (int i = 0; i < numLoops; i++)
{
// do I need to call "delete [] array;" here?
array = new double[arraySize];
}
int x;
std::cin >> x; // pause the program to view memory consumption
delete [] array;
return 0;
}
推荐答案
不,
每次调用 new
或 new []
,一些存储器被分配,并且给出该存储器的地址(以便能够使用它)。每个内存最终必须 delete
d(或 delete []
d)。
Each time you call new
or new[]
, some memory is allocated, and you are given the address of that memory (in order to be able to use it). Each piece of memory must eventually be delete
d (or delete[]
d).
您正在将该地址存储在 array
中,但是在下一次迭代时立即覆盖它。因此,你没有办法 delete
- 你分配的所有内存块。因此,您有内存泄漏。
You are storing that address in array
, but then immediately overwriting it on the next iteration. Therefore you have no way of delete
-ing all of pieces of memory that you've been allocated. Therefore you have a memory leak.
这篇关于在同一个指针上调用new []两次而不调用delete []会导致内存泄漏?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!