Alex Crist
Alex Crist

Reputation: 1099

Objective-c example code that intentionally messages a deallocated object

I'm new to objective-c and xcode and an app I'm currently writing is receiving the infamous EXC_BAD_ACCESS error.

Almost everybody recommends starting to solve the problem using NSZombies. I think I have NSZombies working but xcode isn't giving me an alert about a zombie being messaged when my app crashes.

Before I move on with my debugging, I'd like to run some code that should for sure result in a message being sent to a zombie (de-allocated object).

What is a simple code snippet where a message is sent to a deallocated object, causing a scenario where NSZombies should alert me?

Upvotes: 5

Views: 490

Answers (2)

Tim Johnsen
Tim Johnsen

Reputation: 1501

You could create a CF object, bridge it to an Objective-C object, then release it and try to use the bridged object. I think you have to use __bridge to get this to behave the way you want.

Upvotes: 1

Mark Bessey
Mark Bessey

Reputation: 19782

For non-ARC code:

- (IBAction) messageZombie:(id)sender {
    id a = [[NSObject alloc]init];
    [a release];
    NSLog(@"%@", [a description]);
}

This will give you EXC_BAD_ACCESS with Zombies off, and a "message sent to deallocated instance" message, with Zombies enabled.

If your project is using ARC, then it's a bit harder to reliably-cause messages to de-allocated objects (that is the point of ARC, after all).

This works:

- (IBAction) messageZombie:(id)sender {    
    id a = [[NSObject alloc]init];
    id __unsafe_unretained b =a;
    a=nil;
    NSLog(@"%@", [b description]);
}

It's probably not very similar to what your actual code is doing, because who the heck uses __unsafe_unretained, anyway? But if you just want to make sure that you've got NSZombies turned on properly, this should be a reasonable test case.

If you're looking for suspicious places in your code, then for sure look for __unsafe_unretained pointers, though you won't find any*, and double-check that the right casts are used for CoreFoundation objects that are casted to Cocoa objects.

* If your project needs to support OS X versions before 10.7, or iOS versions earlier than 5.0, then you can't use __weak pointers, so in that sort of project, you'd expect to find __unsafe_unretained used more often.

Upvotes: 7

Related Questions