Search code examples
iosmemory-leakspoolautoreleasensautoreleasepool

Is there any leak in NSAutoreleasepool?


What will be result ? is there any leak or crash??

-(NSString)returnPersonName {
NSAutorelease *pool = [[NSAutorelease alloc]init];
NSString *name = [[[NSString alloc]initWithString:@"Name"]autorelease];
[pool drain];
return name
}

bit confusing to me.


Solution

    1. This code violates memory management rules. You do alloc, so you get ownership of a +1 reference count, and then you do autorelease on it, by which you give up your ownership of the reference count. Therefore, you should not use name anymore, and it is not guaranteed to point to a valid object. You return it, a pointer to a potentially invalid object.
    2. In this particular case, because of the implementation details of Cocoa, nothing "bad" will happen. The body of that function is equivalent to just return @"Name";. @"Name" is a string literal, and string literals are stored in static storage that exists for the entire lifetime of the program. That means those string objects are not subject to memory management -- retain, release on them have no effect. You do [[NSString alloc] init...] on it, but NSString's initializers are optimized to simply retain and return its argument if the argument is already an immutable string. So you are not returning a new NSString object; you are just returning the same string literal which is statically allocated and not subject to memory management. Again, all this is implementation details of Cocoa that you cannot rely on.