views:

198

answers:

5
int main(){

   int * a = new int[10];
   int * b  = new int[10];
   for(int i = 0 ; i < 10; i++)
   {
       a[i] = 1;
       b[i] = 1;
   }

   for(int i = 0 ; i < 10; i++)
   {
       a[i] = b[i]; //each a[i] is allocated 4 bytes on heap
                    //when we copy b[i] into a[i] do we loose 
                    //the reference to a[i] (hence a leak), 
                    //and replace that reference
                    //with a reference to a new value?
   }

   delete[] a;
   delete[] b;


}
+13  A: 

No, there's no leak there. You're just copying values within the array. Think of the arrays as two banks of lockers in a changing room - you're just copying what's in one locker and putting it in a locker in the other bank; the locker itself stays where it is.

Jon Skeet
+1, mostly for starting your answer with the answer ;-)
Michael Krelin - hacker
+5  A: 

[Based on edit] No, there is no leak - you're just be copying over the values, not the pointers. An expression like a[i] means *(a + i); you're looking at (or assigning) the value at that location of memory, not messing with the memory itself.

Jesse Beder
yes sorry thats what I meant
ldog
+3  A: 

a and b are pointers to int. The statements a = 1; and b = 1; are bad. You shouldn't assign integer literals to pointers. Did you mean a[i] = 1; and b[i] = 1;?

Assuming that that's what you meant then no, there is no memory leak.

Jesper
+1  A: 

That is not a memory leak, because you always have reference to the heap allocated memory at a. What would be a memory leak, however, is if, somewhere before your deletes, you said

a = b;

Then, you have nothing pointing to the memory you allocated for a, since both a and b pointed to the memory allocated for b.

Matt
+1  A: 

There is no leak. The pointers a and b are pointing to the first element of appropriate arrays and you don't change the a and b values. What's more you only assing values to elements from those arrays and destroy the array at the end, so everything looks OK.

Simon