Search code examples
objective-cmemory-leaksnsstringanalyzeralloc

How can i resolve this memory leak?



this is my snippet:

- (id) initWithFrame:(CGRect)frame andConfig:(PGParams*) params 
{

 for (int i=0; i<[conf.map count]; i++) 
  [conf.map replaceObjectAtIndex:i withObject:
      [[NSString alloc] initWithFormat:@"%@&sito=%@", 
       [conf.map objectAtIndex:i], [params sito]]];

 for (int i=0; i<[conf.orto count]; i++) 
   [conf.orto replaceObjectAtIndex:i withObject:
      [[NSString alloc] initWithFormat:@"%@&sito=%@", 
       [conf.orto objectAtIndex:i], [params sito]]];

 for (int i=0; i<[conf.mix count]; i++) 
    [conf.mix replaceObjectAtIndex:i withObject:
      [[NSString alloc] initWithFormat:@"%@&sito=%@", 
       [conf.mix objectAtIndex:i], [params sito]]];

}

Compiling this code with RUN_CLANG_STATIC_ANALYZER option (Property->Build Options->Run Static Analyzer), it show me a leak on [[NSString alloc] ....

RUN_CLANG_STATIC_ANALYZER

Activating this setting will cause Xcode to run the Clang static analysis tool on qualifying source files. This tool presently supports C and Objective-C files. [RUN_CLANG_STATIC_ANALYZER]


How can i resolve it?

thanks in advance,
allberto


Solution

  • Right. You're allocating an object that you own (because you invoked +alloc), but then you're never releasing it.

    You can replace all instances of [[NSString alloc] initWithFormat:...] with [NSString stringWithFormat:...] to fix the leak.