Finding EXC_BAD_ACCESS bugs in a Cocoa project
Q:
How do I find EXC_BAD_ACCESS
bugs in a Cocoa project?
A: How do I find EXC_BAD_ACCESS
bugs in a Cocoa project?
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.
Important Factors
If you directly allocate, copy, or retain an object, you are responsible for releasing the newly created object with
release
orautorelease
. 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
andautorelease
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 arelease
or anautorelease
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.
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:
For an overview of Cocoa objects and their life cycles refer to the following guide:
Document Revision History
Date | Notes |
---|---|
2006-10-10 | New document that discusses how to find memory protection violations or EXC_BAD_ACCESS bugs in Cocoa projects. |
Copyright © 2006 Apple Computer, Inc. All Rights Reserved. Terms of Use | Privacy Policy | Updated: 2006-10-10