0

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

Stephen
  • 4,715
  • 8
  • 53
  • 78

4 Answers4

1

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 :)

Community
  • 1
  • 1
Simon Withington
  • 1,485
  • 2
  • 11
  • 17
1

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.)

Hot Licks
  • 47,103
  • 17
  • 93
  • 151
1

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.

georg
  • 211,518
  • 52
  • 313
  • 390
  • mutable strings are usually a bad idea, unless performance suffers. NSString *cmpWorkoutStr = @"" or NSString *cmpWorkoutStr = [[[NSString alloc] init] autorelease]; are basically equivalent, and you need one of them. – Tom Andersen Jan 09 '12 at 20:51
0

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

Stephen
  • 4,715
  • 8
  • 53
  • 78