Re: Exceptions and autorelease pools
Re: Exceptions and autorelease pools
- Subject: Re: Exceptions and autorelease pools
- From: Larry Campbell <email@hidden>
- Date: Tue, 06 Dec 2011 19:08:10 -0500
On Dec 6, 2011, at 4:59 PM, Ken Thomases wrote:
> On Dec 6, 2011, at 2:47 PM, Larry Campbell wrote:
>
>> void allocAndRaise()
>> {
>> [[[NSString alloc] initWithString:@"foo bar and zot"] autorelease];
>> [NSException raise:@"foo" format:@"bar"];
>> }
>>
>> //#define LEAK
>>
>> void foo()
>> {
>> NSAutoreleasePool *pool = [NSAutoreleasePool new];
>> NS_DURING {
>> allocAndRaise();
>> } NS_HANDLER {
>> #ifdef LEAK
>> [localException raise];
>> #else
>> [localException retain]; // I don't think this workaround should be necessary, but it is
>> [pool release];
>> [[localException autorelease] raise];
>> #endif
>> } NS_ENDHANDLER
>> [pool release];
>> }
>
> The workaround is necessary because the exception object raised in allocAndRaise() has been autoreleased. It is no longer owned by anything and is only still around because the pool containing the pending release(s) has not been drained. When you drain it, that executes the pending release(s) and ultimately deallocates it.
By "workaround" I didn't mean just the "[localException retain]", I meant the "[pool release]", without which the retain/autorelease of localException would be unnecessary.
> That is one of the reasons you are discouraged from releasing/draining autorelease pools in exception handlers or @finally blocks.
But if you don't do that, it leaks the pool. Which, though smaller, is still a leak.
For what it's worth, gnustep doesn't leak in this situation. (Well, it has a different leak, for which I just submitted a fix.)
- lc
Attachment:
smime.p7s
Description: S/MIME cryptographic signature
_______________________________________________
Cocoa-dev mailing list (email@hidden)
Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden