A blog post

EXC_BAD_ACCESS, Guard Malloc, and you…

Posted on the 11 March, 2010 at 12:02 pm Written by admin in Blog, Development

We’ve all been there, believing that our code is perfect in every way. But every now and then, the debugger halts with “EXC_BAD_ACCESS” and a stack trace from somewhere deep in the system internals, with not even a line of your code visible. The console output is even less helpful — “debugging terminated” it says, like I didn’t know that. And it doesn’t help that the problem only sporadically occurs.

Tracking down these memory management issues can be quite tricky and consume a lot of time. Often the crash doesn’t occur until well after the offending release or deallocation has occurred. So what’s a deadline-stressed iPhone developer supposed to do? These days, my first reaction is to reach for the magical Guard Malloc lifeline.

Here’s the description from Apple’s developer documentation:

” Guard Malloc is a special version of the malloc library that replaces the standard library during debugging. Guard Malloc uses several techniques to try and crash your application at the specific point where a memory error occurs. For example, it places separate memory allocations on different virtual memory pages and then deletes the entire page when the memory is freed. Subsequent attempts to access the deallocated memory cause an immediate memory exception rather than a blind access into memory that might now hold other data. When the crash occurs, you can then go and inspect the point of failure in the debugger to identify the problem.”

In plain English, what Guard Malloc does is cause your application to crash at or just after any access to the improperly freed memory. In practical use, go to the Run menu in Xcode and select both the “Enable Guard Malloc” and the “Stop on Objective-C Exceptions” menu items. Then run your application and wait for the debugger break to hit. You should get a solid clue as to the data structure or activity causing the issue, and possibly end up staring right at the offending lines of code. Like when a cut-and-paste fumble in your dealloc() routine calls [super dealloc] before releasing your instance memory. Not that that’s happened to any of us recently. Ahem.

For more info on Guard Malloc, see the developer documentation on Apple’s developer site.

-Geoff

reply