Stephen
Stephen

Reputation: 4811

Objective-C Memory Leaks

I'm just investigating some memory leaks in my app, I'm using Xcode 4.0.2. I've run the Analyze tool in Xcode and a good few memory leaks have been identified. I'm relatively new to Objective-C, this is my first app. I've pasted the code here:

http://pastie.org/3155043

I've added comments to the above code, where the memory leaks are occuring.

Memory Leak One: Method returns an Objective-C object with a +1 retain count (owning reference).

Memory Leak Two: Object allocated on line 248 and stored in 'imagesNames' is not referenced later in this execution path and has a retain count of +1 (object leaked).

Memory Leak Three: Potential leak of an object allocated on line 246 and stored into 'cmpWordoutStr'.

Any help appreciated.

Regards, Stephen

Upvotes: 0

Views: 572

Answers (4)

Stephen
Stephen

Reputation: 4811

As Tom Andersen suggested above I used auto release and this solved the problem, example below:

NSString *cmpWorkoutStr = [[[NSString alloc] init] autorelease];
NSString *imageNames = [[[NSString alloc] init] autorelease]; 

Regards, Stephen

Upvotes: 0

georg
georg

Reputation: 214949

You're allocating an object first

NSString *cmpWorkoutStr = [[NSString alloc] init];

and then reassign the pointer without freeing the memory:

cmpWorkoutStr = [cmpWorkoutStr stringByAppendingString:indWorkoutStr];

hence the leak.

I didn't analyze your code in depth, but I guess you actually want NSMutableString there.

Upvotes: 1

Hot Licks
Hot Licks

Reputation: 47699

Leak 1) You don't show the return or identify which variable is returned, so not possible to definitively diagnose this one.

Leak 2) You alloc/init an NSString and assign it to a variable that is never released. This is wrong for two reasons:

  1. For each alloc there must be a corresponding release somewhere.
  2. There is no point in doing alloc/init on an empty string. If you want an empty string just use @"".

Leak 3) Basically the same as (2).

(You really need to get a good book on Objective-C programming and study and restudy the section on storage management. Otherwise you'll be stumbling around in the dark.)

Upvotes: 1

Simon Withington
Simon Withington

Reputation: 1485

You might want to consider using Automatic Reference Counting in your project. I asked a question the other day on here, as I wasn't sure that it was a good idea, but the answers convinced me that it really is a step forward and is well worth taking advantage of:

To ARC or not to ARC? What are the pros and cons?

Hope this helps :)

Upvotes: 1

Related Questions