she swears <i>geek</i> is a term of endearment

Objective C memory exception EXC_BAD_ACCESS likely over-zealous releasing

On this one, I’ll be short and sweet.  Read Apples memory management paper.

Objective C memory management, simplified - or - head, meet wall.  repeat.

Here are the golden rules that I’ve discovered to overcome the EXC_BAD_ACCESS monster.

  1. When you create a pointer, its just a pointer.  for example: NSString *someString;  There’s nothing there yet.  When you assign value, you have a pointer to some allocated memory space.  This is true in all programming languages, we just tend to forget as many modern languages abstract this away from us.
  2. If you reference something that you received from a method, don’t release it.  for example:
    NSArray* resultSet = [entropyRepository queryWithClass: classType];
    I didn’t allocate or create that array, its not mine to release.  When my pointer goes out of scope, it will decrement the reference count.  Whoever created it is ultimately responsible for its release.  It may be auto-released or the creator may have a dealloc method.  However, if you release it, somewhere down the line, the originator may try to access it and you’ll get "EXC_BAD_ACCESS".  Unfortunately, this error will occur sometime in the future, long after you’ve made your mistake.  This was happening to me when the autorelease pool was being processed and I’d already released that array when I was done with it.  Ooops.  There went a week of "head, meet wall.  repeat". 
  3. If you use "alloc", you need to release the referenced memory.  Basically, "alloc" is, "initialize this memory space for me."  If you don’t release it, it’ll just sit there, forever and ever…   You can opt to use autorelease or you can explicitly send a release message. 
  4. In addition to alloc, methods used to get a reference that "create" an object using a method whose name begins with “alloc” or “new” or contains “copy” are yours to release.  This rubs me as hack-a-logical as it leaves so much up to naming conventions.  But, whatever…

One Response to “Objective C memory exception EXC_BAD_ACCESS likely over-zealous releasing”

  1. […] an EXC_BAD_ACCESS error when the autorelease pool was released. As Rusty’s wonderful little blog points out, such an error usually comes from releasing an object that you did not create (does not […]

Leave a Reply