views:

113

answers:

3

If I have the following lines inside a loop:

Type *unite = new Type(newSize); 

or

double *array= new double[anySize];

what is the behavior in what concerns to memory if I don't have delete operators inside it? It will be constantly allocating objects and arrays on different memory locations, and therefore memory leaks?

+12  A: 

Yes it will. This:

for (int i = 0; i < 10; ++i) 
{
  Type* unite = new Type(newSize);
}

will allocate 10 objects of type Type, all at different locations. None of them will be deallocated, and at the end you will not have a pointer to any of them. You will leak 10 * sizeof(Type) bytes of memory.

Similarly, this

for (int i = 0; i < 10; ++i) 
{
  double *array= new double[anySize];
}

will for the same reason leak 10 * anySize * sizeof(double) bytes of memory.

Tyler McHenry
Just a small detail, but shouldn't there be some constant space-overhead for array-allocation, like `10 * anySize * sizeof(double) + c`?
Space_C0wb0y
It's not required that the implementation over-allocate in order to store size information for an array. It's possible that, for example, array size data is stored in a table somewhere that would exist whether or not the allocation took place. So while you're right that there is going to be some overhead also leaked, it's impossible to quantify how much (even something as general as saying `+ c`, since that implies that the overhead grows `O(n)` with allocations, which isn't necessarily true) in a way that applies to all implementations.
Tyler McHenry
+1  A: 

It will be constantly allocating objects and arrays on different memory locations, and therefore memory leaks?

Assuming you mean this:

 for (;x;x)
 {
    double *ptr = new double[42];
 }

Then the answer is yes, the memory is leaked.

Billy ONeal
+1  A: 

Yes. You will leak memory at every iteration of your loop. boost::scoped_ptr and boost::scoped_array are made to handle such situations.

Space_C0wb0y