EXC_BAD_ACCESS Problem In Objective-C

EXC_BAD_ACCESS memeSo you finally stumbled upon this error. If you have been working with Objective-C, this is bound to happen. When you release the memory of an object that has already been released, and then try to go back to your previous UIViewController, you will encounter this error. One of the possible reasons could be that you must be using Automatic Reference Counting (ARC) in your project. ARC was a new feature introduced in iOS 5.0 to take care of memory management. This is a very useful feature, but it can also cause errors if you don’t understand what’s happening under the hood.  

How do I fix it?

You can fix the error by simply disabling ARC. To disable it, do the following:

  • Click on your project, in the left hand organizer.
  • Select the “Build Settings” tab at the top.
  • Scroll down to “Objective-C Automatic Reference Counting” (it may be listed as “CLANG_ENABLE_OBJC_ARC” under the User-Defined settings group),
  • Set it to NO.

And we are done! If you want to know more about the memory management, read on. If you are new to Objective-C or come from a different programming background, it can take a little while before you really understand the nuts and bolts of the memory management rules. Whenever you get something from an allocation function (usually the static alloc method), or a copy method, you own that memory. Hence, you are responsible for releasing it when you are done.

Autorelease Reference

If you get something back from anything in Objective-C, be it classes, functions, or factory methods, you’ll have an autorelease reference. It means that it could be released at some time in the future by other code. This is a good thing as long as you control it. But it is important to know that if you need to keep it around beyond the immediate function, you need to retain it. You can read about “@property” directive and the “retain” functionality to learn more about it.

What happens if you don’t retain it?

As it turns out, things are different when you run your code on an emulator vs an actual device. If you don’t retain it, then the memory may remain allocated while you are using it, or may be released but coincidentally still valid during your emulator testing. It is more likely to be released and then show up as bad access errors when running on the device. The best way to track these things down is to run the app in the Instruments tool, with the Leaks option. It is very helpful in tracking these memory issues.


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s