John Wu
John Wu

Reputation: 1025

Object still available when reference counting is 0

Sorry if this is an duplicated entry, I am new to OC.
I have turned off "Object-C Automatic reference counting" in build settings. And I have two classes Guitar and GuitarController.
GuitarController.m looks like this:

#import "GuitarController.h"

@implementation GuitarController

-(void) setGuitar:(Guitar*) newGuitar
{
    guitar = newGuitar; 
    // Yes, i did not retain the guitar object. 
    // I did it on purpose to test whether something will go wrong
}

-(void) playGuitar
{
    [guitar play];
}
@end

and Guitar.m looks like this:

#import "Guitar.h"

@implementation Guitar
-(void) play
{
    NSLog(@"play guitar!!!");
}
@end

finally, the main.m code:

#import <Foundation/Foundation.h>
#import "GuitarController.h"

int main(int argc, const char * argv[])
{
    Guitar* guitar = [[Guitar alloc] init];
    GuitarController* guitarController = [[GuitarController alloc] init];
    [guitarController setGuitar:guitar];
    [guitar release]; 
    [guitarController playGuitar]; // Expecting an error here
    return 0;
}

The code above works just fine. But it is obviously wrong because I referenced an Object after its reference count became 0. Any clues? Thanks!

Upvotes: 1

Views: 55

Answers (1)

Rob Napier
Rob Napier

Reputation: 299265

It's very likely that the guitar has not been returned to the OS yet. That's very normal. Real memory allocations are expensive. Cocoa avoids them when it can. For such a tiny object, Cocoa almost certainly just stuck it in its private pool to allocate again later. That means your application still technically owns the memory, so accessing it is totally legal, and you won't get an exception. See A look at how malloc works on the Mac for more details on that.

Accessing memory after you've released it is undefined behavior. You cannot "expect" anything after you do that. The computer can catch on fire, and that would be considered in spec. The program can also continue to work perfectly. That would also be in spec. The system makes you no promise that you will receive an error.

I hope that you have turned off ARC simply to try to learn a little more about the underlying system. If so, that's fine. But for any serious program you should turn on ARC.

Upvotes: 3

Related Questions