I just noticed a surprising behavior of NSArray
, that's why I'm posting this question.
I just added a method like:
- (IBAction) crashOrNot
{
NSArray *array = [[NSArray alloc] init];
array = [[NSArray alloc] init];
[array release];
[array release];
}
Theoretically this code will crash. But In my case it never crashed !!!
I changed the NSArray
with NSMutableArray
but this time the app crashed.
Why this happens, why NSArray
not crashing and NSMutableArray
crashes ?
In general, when you deallocate an object the memory is not zeroed out, it’s just free to be reclaimed by whoever needs it. Therefore if you keep a pointer to the deallocated object, you can usually still use the object for some time (like you do with your second -release
message). Sample code:
#import <Foundation/Foundation.h>
@interface Foo : NSObject
@property(assign) NSUInteger canary;
@end
@implementation Foo
@synthesize canary;
@end
int main(int argc, const char * argv[])
{
@autoreleasepool {
Foo *foo = [[Foo alloc] init];
[foo setCanary:42];
[foo release];
NSLog(@"%li", [foo canary]); // 42, no problem
}
return 0;
}
There are no checks against this by default, the behaviour is simply undefined. If you set the NSZombieEnabled
environment value, the messaging code starts checking for deallocated objects and should throw an exception in your case, just as you probably expected:
*** -[Foo canary]: message sent to deallocated instance 0x100108250
By the way, the default, unchecked case is one of the reasons why memory errors are so hard to debug, because the behaviour might be highly non-deterministic (it depends on memory usage patterns). You might get strange errors here and there around the code, while the bug is an over-released object somewhere else. Continuing in the previous example:
Foo *foo = [[Foo alloc] init];
[foo setCanary:42];
[foo release];
Foo *bar = [[Foo alloc] init];
[bar setCanary:11];
NSLog(@"%li", [foo canary]); // 11, magic! (Not guaranteed.)
As for why is NSArray
different from NSMutableArray
, an empty array looks like a special beast indeed:
NSArray *foo = [[NSArray alloc] init];
NSArray *bar = [[NSArray alloc] init];
NSLog(@"%i", foo == bar); // yes, they point to the same object
So that might have something to do with it. But in general case, working with deallocated objects might do anything. It might work, it might not, it might spill your coffee or start a nuclear war. Don’t do it.
The simplest thing I can think of is that an empty NSArray
is some kind of "constant" in the Foundation framework - e.g. an object similar to a NSString
literal, which would have a retainCount
(if you were to invoke it) of -1, and it could never be -dealloc
'd.
来源:https://stackoverflow.com/questions/13233853/why-can-i-send-messages-to-a-deallocated-instance-of-nsarray