[cs13001] Memory leak?

Mikhail Nesterenko mikhail at cs.kent.edu
Sat Nov 17 19:58:56 EST 2012


> 
> Why does this lead to a memory leak?

> int *ptr = new int;
> ptr = new int; 
> 

Because the pointer to the first dynamically allocated integer
variable gets re-assigned to point to the second one hence leaking
(there is no way to refer to it) the first one.


    > Another problem I'm facing is in this code I was writing:
    > 
 1  >     int a[10], *p1, *p2;
 2  >     p1 = a;
 3  >     p1[2] = 5;
 4  > 
 5  >     cout << a[2] << ' ' << p1[2] << endl;
 6  >     
 7  >     p1[20];
 8  >
 9  >     cout << p1;
 10  >     p1[19] = 55;
 11  >     cout << a[19] << ' ' << p1[19];  <<<<<<<<<<<<<<<<<<<<
     > 
     > Why does a[19] output the value of 55 with some arbitrary
     > numbers before it ? Something like 09EX453WA55.

This is how out of range error manifests itself. It looks like you are
allocating an array of 10 elements an then, in lines 7 and 11 refer to
the 21 and 20-ieth elements.

Thanks,
--
Mikhail


More information about the cs13001 mailing list