Kochan Book Example Help - memory Leakage

Discussion in 'Mac Programming' started by Barbariska, Apr 5, 2008.

  1. Barbariska macrumors member


    Dec 28, 2007
    I am learning ObjC using very well written book by Mr. Kochan. There is an example 7.7 in the book that sums fractions. The code is listed below.

    There is a Free statement for Objects aFraction and sum, but there is no free for sum2 and I can't understand it how it is being freed. Why not for sum2? Where it is being freed? Please help! Also the remark in the book is that "The result from add: method is assigned to sum2 and not to sum to avoid memory leakage". Please can somebody explain step by step on this example the life cycle of objects sum and sum2. THANKS!!!!


    -(Fraction *) add: (Fraction *) f
    Fraction *result = [[Fraction alloc] init];
    int recultNum, resultDenom;
    resultNum = (numerator * [f denominator]) + (denominator * [f numerator]);
    resultDenom = denominator * [f denominator];

    [result setTo: resultNum over: resultDenom];
    [result reduce];
    return result;

    Here is main.m where the method is used:

    #import "Fraction.h"

    int main (int argc, char *argv[])
    Fraction *aFraction = [[Fraction alloc] init];
    Fraction *sum = [[Fraction alloc] init], *sum2;

    int i, n, pow2;

    [sum setTo: 0 over: 1];

    scanf ("%i", &n);
    pow2 = 2;
    for (i = 1; i <= n, ++1)
    [aFraction setTo: 1 over: pow2];
    sum2 = [sum add: aFraction];
    [sum free];
    sum = sum2;
    pow2 * = 2;

    printf (After %i iterations, the sum is %g/n", n, [sum converToNum]);

    [aFraction free];
    [sum free];

    retun 0;

  2. phjo macrumors regular

    Jan 8, 2008
    What the line sum = sum2 does is just a copy of the reference sum2 (it is just that, a pointer to a Fraction object) to sum. So by freeing sum afterwards, you ARE freeing the memory the object referenced by sum2 occupied...

    Now if you did :

    sum = [sum add: aFraction];

    then according to the code you pasted, you would have created a new Fraction object and copy its reference to the sum pointer, replacing the Fraction's reference sum contained then, so there is no reference anymore to that object, and no way to free it.


Share This Page