Re: static analyzers says I'm leaking, I _think_ I'm not
Re: static analyzers says I'm leaking, I _think_ I'm not
- Subject: Re: static analyzers says I'm leaking, I _think_ I'm not
- From: Ken Thomases <email@hidden>
- Date: Wed, 06 May 2015 16:20:48 -0500
On May 6, 2015, at 3:57 PM, Michael David Crawford <email@hidden> wrote:
> // LifeGrid.h
> @property (assign, nonatomic) GridCycler *cycler;
>
> // Lifegrid.m - init
> self.cycler = [[GridCycler alloc] initWithGrid: self]; // Potential
> leak of an object
> if ( nil == self.cycler ) goto cycler_failed;
>
> // dealloc
> [self.cycler release];
>
> Expanding the "potential leak" message yields:
>
> 1. assuming 'self' is not nil
>
> 2. method returns Objective-C object with +1 retain count
>
> 3. Object leaked: allocated object is not references later in this
> execution path and has a retain count of +1.
>
> Isn't that what I want? I should be taking ownership of it with
> "alloc/initWithGrid".
>
> (initWithGrid doesn't do a cyclic retain.)
You are probably also getting an analyzer warning in -dealloc saying the getter of self.cycler returns an object you don't own so you're not entitled to release it.
What you're doing will not be a leak if the cycler property is implemented in the "normal" way. But what if -setCycler: stores something derived from but not the same as what was passed in? Then, you would fail to release what was passed in (the leak) and you'd be releasing something which you don't own in -dealloc.
Now, you may be thinking that the code for the cycler property is all right in this same class. It's likely even auto-synthesized by the compiler so you have no hand in it. But what if there were a subclass which overrides the accessors? What if the subclass's -setCycler: took the passed-in object, created a new object that was a tweaked version of it, and passed the new object to the superclass's -setCycler:?
If you're looking to make this code better, change the property to be strong. Change this line:
self.cycler = [[GridCycler alloc] initWithGrid: self];
to
self.cycler = [[[GridCycler alloc] initWithGrid: self] autorelease];
and, in -dealloc, release the instance variable, not the result of the getter.
Regards,
Ken
_______________________________________________
Cocoa-dev mailing list (email@hidden)
Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden