Shane Hou
Shane Hou

Reputation: 5018

EXC_BAD_ACCESS in main( )

I got an EXC_BAD_ACCESS in main(), here is my code:

int main(int argc, char *argv[])
{
    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
    int retVal = UIApplicationMain(argc, argv, nil, @"TestBedAppDelegate");
    [pool release];
    return retVal;
}

@interface TestBedAppDelegate : NSObject <UIApplicationDelegate>
@end

@implementation TestBedAppDelegate
- (void)applicationDidFinishLaunching:(UIApplication *)application {    
    UIWindow *window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:[[TestBedViewController alloc] init]];
    [window addSubview:nav.view];
    [window makeKeyAndVisible];
}
@end

- (void) action: (id) sender
{
    [self highRetainCount];
}

@implementation TestBedViewController
- (void) highRetainCount
{
    UIView *view = [[[UIView alloc] init] autorelease];
    printf("Count: %d\n", [view retainCount]);

    NSArray *array1 = [NSArray arrayWithObject:view];
    printf("Count: %d\n", [view retainCount]);
    [array1 autorelease]; // If comment this line, everything will be OK
}
@end

The program stopped at main():

int retVal = UIApplicationMain(argc, argv, nil, @"TestBedAppDelegate");

As the comment says, after commenting out [array1 autorelease];, everything was OK.

So here is my question:

  1. EXC_BAD_ACCESS often indicates using an object already released. Clearly there's something to do with [array1 autorelease];, but I can't understand their relationship.

  2. Why stopped at this position -- main() -- instead of somewhere else?

Newbie question :)

Upvotes: 2

Views: 349

Answers (1)

Kristian Glass
Kristian Glass

Reputation: 38510

arrayWithObject: returns an object you do not own. Therefore it is wrong for you to subsequently send it autorelease.

See the Basic Memory Management Rules, specifically:

  • You must not relinquish ownership of an object you do not own

and

  • You own any object you create

You create an object using a method whose name begins with “alloc”, “new”, “copy”, or “mutableCopy” (for example, alloc, newObject, or mutableCopy).

Also, as a more general point, don't use retainCount. Unless you happen to be doing low-level hacking of the runtime or something, you don't need it, and it won't return anything of use to you.

Upvotes: 5

Related Questions