Debugging BAD_ACCESS with NSZombieEnabled

Everyone who had to debug a segmentation fault within an application, knows, how tricky it can be to detect such a bug. The reason for that is, that in most cases the crash doesn’t occur in the line of code where the actual bug is. Instead your application crashes somewhere else, usually in some piece of code which doesn’t have anything to do with the code that contains the bug.

Fortunately, Cocoa offers a cool feature which greatly enhances your capabilities to debug such situations. It is an environment variable which is called NSZombieEnabled. When set to YES,this variable causes Cocoa actually not to release an object after it has received a release message. Instead Cocoa just “remembers” that the object has received the release message
and on any subsequent messege sent to this object, a log message
is pribted to the console and SIGTRAP is thrown. The debugger immediately interrupts your application when you try to access an invalid object. A backtrace shows you the exact line of code which caused the BAD_ACCES.

To enable NSZombieEnabled simple open the Info panel of your application executable within XCode and set it to YES.

How to enable NSZombieEnabled

Now write some lines of code to see how it works:

1
2
3
4
NSDate *date = [NSDate date];
NSLog(@"Date: %@", date); /* good access */
[date release];
NSLog(@"Date: %@", date); /* bad access, causes a crash */

Now, if you run this code inside the debugger, your application will stop when the bad access occurs and with a backtrace you can easily find the line of code which caused it.

See exactly where it crashed

Cool, isn’t it?
Remember to turn of NSZombieEnabled after you have finished the debugging.

This entry was posted in Uncategorized and tagged , , , . Bookmark the permalink.

Warning: count(): Parameter must be an array or an object that implements Countable in /home/httpd/vhosts/shrdlu.ch/shrdlu.ch/wp-includes/class-wp-comment-query.php on line 405

2 Responses to Debugging BAD_ACCESS with NSZombieEnabled

  1. Chuan says:

    Hi, Thanks for your post, but I have got some problems in using NSZombieEnabled.
    Just as you said, there is an “EXE_BAD_ACCESS” in my program, and I have set the NSZombieEnabled in my execute file, but the program just crash without leaving any helpful messages but “EXE_BAD_ACCESS”, how could this come from?

  2. michael says:

    Hi Chuan,

    I don’t know why you’re not getting anything useful. Without knowing any details about what you’re trying to do it is difficult to make any assumptions.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.