
August 23rd, 2010, 04:53 PM
|
 |
Contributing User
|
|
Join Date: Jan 2010
Location: Katy, Texas
|
|
Quote: | Originally Posted by thomashw I've bolded the part of the code I don't fully understand. - Won't sum = sum2 just overwrite the old sum? So why do you need to release it beforehand?
- Why isn't sum2 released at the end of the program? Should it be?
Code:
#import “Fraction.h”
int main (int argc, char *argv[])
{
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
Fraction *aFraction = [[Fraction alloc] init]; Fraction *sum = [[Fraction alloc] init], *sum2; int i, n, pow2;
[sum setTo: 0 over: 1]; // set 1st fraction to 0
NSLog (@”Enter your value for n:”);
scanf (“%i”, &n);
pow2 = 2;
for (i = 1; i <= n; ++i) {
[aFraction setTo: 1 over: pow2];
sum2 = [sum add: aFraction];
[sum release]; // release previous sum
sum = sum2;
pow2 *= 2;
}
NSLog (@”After %i iterations, the sum is %g”, n, [sum convertToNum]); [aFraction release];
[sum release];
[pool drain];
return 0;
}
|
Since sum and sum2 are both pointers to instances of Fractions, all
will do is overwrite the pointer contained in sum, thus causing a memory leak to the instance that sum used to point to. You need to release it before the assignment of sum2. Remember, the setTo method in Fraction.h will return a pointer to a new instance of Fraction.
sum2 could have been released at the end of the program, as both sum and sum2 point to the same instance.
|