Apple Developer Connection
Advanced Search
Member Login Log In | Not a Member? Contact ADC

Technical Q&A QA1367
Finding EXC_BAD_ACCESS bugs in a Cocoa project

Q: How do I find EXC_BAD_ACCESS bugs in a Cocoa project?

A: This kind of problem is usually the result of over-releasing an object. It can be very confusing, since the failure tends to occur well after the mistake is made. The crash can also occur while the program is deep in framework code, often with none of your own code visible in the stack.

Summary

To avoid problems like this, you must follow the Cocoa memory management rules. Refer to ADC's document "Memory Management Programming Guide for Cocoa". The section “Object Ownership and Disposal” describes the primary policy.

Back to Top 

Important Factors

  • If you directly allocate, copy, or retain an object, you are responsible for releasing the newly created object with release or autorelease. Any other time you receive an object, you are not responsible for releasing it.

  • A returned object is normally guaranteed to remain valid within the method it was received in (exceptions include multithreaded applications and some Distributed Objects situations). That method may also safely return the object to its invoker.

  • If you need to store a returned object in an instance variable, you must retain or copy it.

  • Use retain and autorelease when needed to prevent an object from being invalidated as a normal side-effect of a message.

  • If you instantiate an object using a convenience method, the object is already slated for autorelease. Do not send a release or an autorelease message to this object.

  • Never send a dealloc message to the object. This may dispose of the object but it does so regardless of the current reference count. Any other object that has retained the deallocated object is left with an invalid reference.

  • Never make any assumptions on how or in what order autoreleased objects are disposed.

Back to Top 

Technical Documentation

For information on a debugging tool called NSZombieEnabled to help isolate this kind problem, as well as other debugging tips, refer to:

Technical Note 2124 Mac OS X Debugging Magic

This topic is also mentioned in the ADC Reference Library documentation:

Memory Management Rules

For an overview of Cocoa objects and their life cycles refer to the following guide:

The Life Cycle of a Cocoa Object

Back to Top 

Document Revision History

DateNotes
2006-10-10First Version

Posted: 2006-10-10




Did this document help you?
Yes: Tell us what works for you.

It’s good, but: Report typos, inaccuracies, and so forth.

It wasn’t helpful: Tell us what would have helped.