Debugging memory based crashes on iPhone

On my Atalasoft blog, I wrote some tips for debugging unmanaged crashes in .NET. The idea is the same for iPhone — namely:

The corollary to this tip is to get it to crash as early as possible. It’s no fun to figure out a crash bug once the culprit function has already returned. You really want the root cause somewhere on the call stack when it’s detected.

In XCode, it’s actually really easy to get information about how you might be managing memory incorrectly.

If you think you are having an issue where you go out of bounds of a heap allocated memory block, then in the Run menu, you can check “Enable Guard Malloc”. This will tell you if you overrun your bounds. It’s not going to be as handy as a Page Heap style check (where each heap allocation gets its own page and therefore crashes at the point of the mistake), but it’s better than nothing.

Go to Project->Edit Active Executable, go to the Arguments tab and in the environment variables section, add

NSAutoreleaseFreedObjectCheckEnabled
NSZombieEnabled
NSDebugEnabled

And set each to YES. You can leave them there unchecked, but if you check them, then your application will now do some extra checking on autorelease and release and give you a good stack trace when you have done it wrong. A common problem is to think you need to call release when the object is already set to autorelease (see yesterday’s post on what the rules are for that).

Also, I haven’t needed it yet for the iPhone, but MallocDebug is supposedly available for use when you debug through the device. I have used it for regular applications and it’s quite good at finding heap corruption problems.