19/10/09

About EXEC_BAD_ACCESS error

Filed under: iPhone Dev SDK by Marc @ 09:08

I know that It’s been so far since my last post, but I have been very very very busy since then, but I’m here again, this time to talk about the EXEC_BAD_ACCESS error.

This kind of error is hard to debug, it happens when a message is sent to a released object, but the Xcode debugger doesn’t give any kind of information about which is the released object, because it is already released and it isn’t allocated in memory anymore, so the debugger doesn’t know it’s structure and it only has a pointer to an “empty” memory address. As the application can crash at anytime before the object is released it seems to be quite aleatory and sometimes hard to reproduce and trace.

So ’cause each EXEC_BAD_ACCESS error is different depending on your specific source code, I can’t give a generic solution, but I can explain you a way to trace it. you should know that exists an environment variable called NSZombieEnabled. If you set it to yes, Objective-C will leave in memory a dummy object for each deallocated object, then if your application send a message to the zombie object, execution will stop and you will be able to take a look at the stack and see from where the object is called. It can’t tell you the specific line of your source where the object is released, but it shows you the method where your object is called before being released and this should you get an idea of where the problem is.

So I imagine that now you are wondering hot to set up this variable, so let’s go on. To do it you have to create a new instance variable right clicking on your executable name, inside the executables group on the left side column of your Xcode’s project screen. Then choose the get info option. Then tap on the Arguments tab. You will see to white boxes, the second one is the one to set up environment variables, so press the + symbol under the white box and name the variable NSZombieEnabled with the word YES as the value. Make sure the checkbox is selected.

So you just have to run your application in debug mode, next time the EXEC_BAD_ACCESS occurs, the application will stop and you will see this kind of message in the debugger console:

2009-10-19 09:33:00.000 xxxxx[3997:20b] *** -[YourObject retain]: message sent to deallocated instance 0xXXXXXXX

Now you are able to click on the debugger and take a look at the stack. You will see some methods in bold, these are the ones you should take a look to review where your object is called after being released.

Remember that you have to uncheck the checkbox of the NSZombieEnabled variable once you fix the problem, or delete the variable if you prefer, or you will experience memory crashes, because of the zombie objects allocated and never freed.



No Comments

No comments yet.

RSS feed for comments on this post. TrackBack URL

Sorry, the comment form is closed at this time.