2

The Xcode debug memory graph tool has detected leaks for deallocated cocoa objects as you see in code below. Basically it happens whenever an exception is caught in a block where you allocate cocoa objects. You can give it a try using using any sdk, here is macOS 11.1, although iOS 14.4 sdk will produce the same result. You can add a breakpoint just after the end of object scope and launch Debug Memory Graph to see the leaked NSString object. What do you think, actually a bug or missed something?

@interface TestClass : NSObject

- (void)testMethod;

@end

@implementation TestClass

- (void)testMethod {
    @try {
        NSMutableString *string = [NSMutableString new];
        NSLog(@"%p: %@", string, string);
        @throw [NSException exceptionWithName:@"exception1" reason:@"exception1" userInfo:nil];
    } @catch(NSException *exception) {
        NSLog(@"%@", exception);
    }
}

- (void)dealloc {
    NSLog(@"dealloc method called!");
}

@end

int main(int argc, const char * argv[]) {
    @autoreleasepool {
        {
            TestClass *testClass = [[TestClass alloc] init];
            [testClass testMethod];
        }
        NSLog(@"byebye");
    }
    return 0;
}

Console output:

0x1006a6330: whatever
exception1
dealloc method called!
byebye

Leaked objects summary in Issue navigator pane

LeakTest - 11521 Group
Memory Issues - (2 leaked types) Group
runtime: Memory Issues - (2 leaked types): 1 instance of __NSCFString leaked
    0x1006a6330
runtime: Memory Issues - (2 leaked types): 1 instance of CFString (Storage) leaked
    0x1006a63a0

Contents of leaked CFString object in Quick Look context menu item

po [(NSString *)0x1006a6330 debugDescription]
whatever
asir
  • 21
  • 3

1 Answers1

0

This is expected behavior. ARC is not not exception-safe in most cases. It's possible to turn on exception handling for ARC by passing -fobjc-arc-exceptions (and it's turned on by default in Objective-C++), but it has significant costs. Objective-C exceptions are not intended as a general-purpose error-handling mechanism (such as Swift throws or C++ exceptions). As noted in the Exceptions section of the ARC documentation:

The standard Cocoa convention is that exceptions signal programmer error and are not intended to be recovered from. Making code exceptions-safe by default would impose severe runtime and code size penalties on code that typically does not actually care about exceptions safety. Therefore, ARC-generated code leaks by default on exceptions, which is just fine if the process is going to be immediately terminated anyway. Programs which do care about recovering from exceptions should enable the option.

For information on standard error-handling patterns in Objective-C, see Dealing with Errors in Programming with Objective-C.

Rob Napier
  • 286,113
  • 34
  • 456
  • 610