Search code examples
iosobjective-cexc-bad-access

How to reproduce EXC_BAD_ACCESS in generic case


I've been playing around in Objective-C and was trying to purposefully get a EXC_BAD_ACCESS crash. What are some sure ways to achieve this?

I read that Whenever you encounter EXC_BAD_ACCESS, it means that you are sending a message to an object that has already been released. What is meant by the phrase "sending a message to an object"?

Something that I tried to achieve the crash but did not succeed:

 __weak NSMutableArray *array;
    NSLog(@"%@", array)
    [array insertObject:@2 atIndex:0];
    NSLog(@"%@", array.firstObject)

Solution

  • You are sending insert:atIndex: to array.

    The code does not crash because in Objective-C it's allowed to send a message to nil.

    array is nil because it's declared but not initialized (yet).


    You can reproduce a crash by declaring an object property with assign attibute

    @property (assign) NSMutableArray *array;
    

    Then create a method

    - (void)insertSomething {
        self.array = [NSMutableArray array];
        [self.array insertObject:@2 atIndex:0];
    }
    

    and call it

    [self insertSomething];
    NSLog(@"%@", self.array.firstObject);
    

    Due to the assign attribute array is a weak reference and gets released right after leaving the insertSomething method.