Sanoj Kashyap
Sanoj Kashyap

Reputation: 5060

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.

Upvotes: 2

Views: 60

Answers (2)

Bamsworld
Bamsworld

Reputation: 5680

I'm tipping the above could potentially crash because [pool drain] will cause name to be deallocated before it can be returned.

In a reference-counted environment, the drain method behaves the same as release. Since an autorelease pool cannot be retained, this therefore causes the receiver to be deallocated. When an autorelease pool is deallocated, it sends a release message to all its autoreleased objects. If an object is added several times to the same pool, when the pool is deallocated it receives a release message for each time it was added.

The pool is not required, for something like this try -

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

More info can be found in the Advanced Memory Management Programming Guide

On a side note - an @autorelease { } pool block is better to use than NSAutoreleasePool and even better is switch to ARC!

Upvotes: 2

newacct
newacct

Reputation: 122439

  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.

Upvotes: 3

Related Questions