0
void test(void) {
    @autoreleasepool {
        NSDictionary *dict = copyDict();
        NSLog(@"%lu", [dict retainCount]);
        [dict release];
    }
}

int main (int argc, const char * argv[])
{
    test();
}

The above code is compiled without ARC and calls into a framework function - copyDict() that's compiled with ARC:

NSDictionary *copyDict(void) {
    
    NSString *path = @"/var/root/dict_file";
    
    NSDictionary *dict = @{
        @"a":@"a"
    };
    
    [dict writeToFile:path atomically:YES];
    
    return [[NSDictionary alloc] initWithContentsOfFile:path];
}

When I run it, it always runs into an EXC_BAD_ACCESS error here as the autorelease pool drains:

for: objc_autoreleasePoolPop
->  0x104aa0058 <+88>: ldp    x29, x30, [sp, #0x20]
    0x104aa005c <+92>: add    sp, sp, #0x30
    0x104aa0060 <+96>: retab  

I tried deleting [dict release] and that fixed it or deleting the autorelease pool.

However, I don't understand why I'm not supposed to release it manually. And as I understand it, the copyDict() function, while being compiled, would be compiled automatically by the clang compiler into returning a singly retained object cus I prefixed it with the copy keyword. Also, what baffles me is that the printed retain count is 2 instead of 1. Can someone help explain why this's happening?

4
  • See retainCount: "This method is of no value in debugging memory management issues". Commented Jun 25 at 10:31
  • See Return NSString from a C function Commented Jun 25 at 12:42
  • This question is similar to: Return NSString from a C function. If you believe it’s different, please edit the question, make it clear how it’s different and/or how the answers on that question are not helpful for your problem. Commented Jul 23 at 15:16
  • If the code is compiled with ARC, copyDict() will return autoreleased already, as it's not marked NS_RETURNS_RETAINED. If the caller is also ARC, I think the runtime uses a trick to release directly rather than autorelease, but the end result is the same. You are releasing an already-autoreleased object, so it's an extra release. Commented Sep 26 at 20:59

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.