ctaggart
ctaggart

Reputation: 166

Leaking Method in Objective C

I'm working through Stephen Kochan's Programming in Objective-C (which is to confess that I'm a complete beginner).

My current program is a fraction calculator. I have add, subtract, multiply, and divide methods. Instruments tells me they're all leaking (only a tiny bit, but it's a tiny program.)

Here's the definition of the subtraction method (the rest follow a very similar form):

-(Fraction *)   subtract: (Fraction *) f;
{
    Fraction    *result = [[Fraction alloc] init];
    int         resultNum, resultDenom;

    resultNum = numerator * f.denominator - f.numerator * denominator;
    resultDenom = denominator * f.denominator;

    [result setTo: resultNum over: resultDenom];

    return result;
    [result release];
}

Thoughts to plug the leak? Thanks ahead of time.

Also, I looked around for another explanations on the site, but sadly, I don't think anyone else has asked anything so basic.

Upvotes: 3

Views: 210

Answers (2)

Junior Bill gates
Junior Bill gates

Reputation: 1866

Replace:

return result;
[result release];

With:

return [result autorelease];

Upvotes: 4

user557219
user557219

Reputation:

The problem is that in:

return result;
[result release];

-release is never sent to result because any statement after return isn’t executed. Such statements are called dead code.

You should autorelease your object, e.g.:

return [result autorelease];

Note that you should use -autorelease instead of -release because -release would cause the immediate deallocation of result, which is not what you want. An autoreleased object, on the other hand, is released at some point in the future — specifically, when the corresponding autorelease pool is drained.

Upvotes: 8

Related Questions