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.
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.
Cool, isn’t it?
Remember to turn of NSZombieEnabled after you have finished the debugging.