views:

255

answers:

1

Hi, i'm have this code for initialize my class.

- (id)initWithSize:(int)size {

    self = [super init];

    if( self != nil )
    {
     [self setMyVector:[[NSMutableArray alloc] initWithCapacity:size]];

     for ( int i = 0; i < size; i++ ) 
     {
      [myVector addObject: [[NSMutableArray alloc] initWithCapacity:size]];
     }
    }

    return self;
}

I'm get this leak in Instruments !
Category: CFArray (store-deque)
Event Type: Malloc

Anyone know what i need to resolve it ? Thanks !

+5  A: 

The leak is in your for loop, and possibly also one before.

First, this line:

[self setMyVector:[[NSMutableArray alloc] initWithCapacity:size]];

If setMyVector retains the passed array (which, according to convention, it probably should), then you've leaked the array. First you alloc and init the array. It has a retain count of +1. Then you set it into the myVector instance variable, which means it has a retain count of +2. When you put something else into myVector, or you release the myVector variable in your dealloc method, you're going to decrement the retain count, which means it'll have a retain count of +1. In other words, it won't be deallocated, and you've leaked the array.

The other, definite leak is inside your for() loop, where you have:

[myVector addObject: [[NSMutableArray alloc] initWithCapacity:size]];

Again, you create an array with a retain count of +1, then you add it to the myVector array, which will retain it again (+2). However, you no longer have a pointer to the array, so you've leaked it.

Both of these leaks can be solved by using [NSMutableArray arrayWithCapacity:size] instead of the alloc/init approach. This will create an autoreleased array, which will solve your memory leak.

If you don't know what autoreleasing is, then you may want to consider creating the array and storing it into a local variable, adding it to myVector (or setting it into myVector), and then immediately releasing it afterwards.

Dave DeLong
Very thanks, i'ts work !
Hitcurst