please help to figure this out.
I have some leaking code, and I don’t know how to handle it
vector <ItemClass> items( 10 );
items[1] = ItemClass( "DVD Player", 560 );
items[5] = * new ItemClass( "Blu Ray Player", 900 );
How should I free memory for items[5] ?
I’m getting error on my attempts of freeing memory
delete &items[5];
delete [] &items[5];
I even tried something like
ItemClass * delItem = &items[5];
items[5] = item4;
delete delItem;
I’m getting “corruption of the heap” in VS2010 Ultimate
There is a strange use and mix up of storing new-allocated objects in vectors in your code. Usually you should handle lists all in the same way. Thus my examples below will be more explicit, and independent from each other which should help you understand the differences.
Use
deletefor objects only. See code below.Use
delete []for “native” arrays only, not for vector or similar container classes or objects inside them.I will not give an example for arrays though, since arrays might be more confusing.
Default example stack:
Default example with heap allocation:
The following examples should be avoided and are for clarifying things up only! Use at own risk.
Storing addresses of stack variables:
If you mix up with the example before and store references and pointers you must handle it yourself. My recommendation: Do not do this.
Storing dereferenced items: