How to find the cause of a malloc “double free” error?

When an object is “double-freed”, the most common cause is that you’re (unnecessarily) releasing an autoreleased object, and it is later autoreleased when the containing autorelease pool is emptied.

I’ve found that the best way to track down the extra release is to use the NSZombieEnabled environment variable for the affected executable in Xcode. For a quick rundown of how to use it, check out this CocoaDev wiki page. (In addition to this page, Apple has documented some incredibly obscure yet useful tips for debugging code in Xcode, some of which have saved my bacon more than a few times. I suggest checking out this Technical Note on developer.apple.com — link jumps to the section on Cocoa’s Foundation framework).

Edit: You can often track the offending object down within the Xcode debugger, but it’s often much easier if you use Instruments to assist you. From Xcode, choose Run → Start With Performance Tool → Object Allocations and you should be able to trace the offending object back to where it was created. (This will work best if you’re enabled zombies as discussed above.) Note: Snow Leopard adds a Zombies tool to Instruments, accessible from the Run menu as well. Might be worth the $29 alone! 😉

There is also a related SO question here.

Leave a Comment