Finding memory leaks in Xcode

I have found over time I have collected a set of environment variables and arguments that I end up leaving in the Arguments window of an executable so that I can quickly turn them on and off when I need them.

Arguments to be passed on launch:

  • -com.apple.CoreData.SQLDebug 1

Variables to be set in the environment (The values for all variables should be set to YES):

  • NSZombieEnabled
  • NSDebugEnabled
  • MallocStackLogging
  • MallocStackLoggingNoCompact

I should be clear that whilst I leave these parameters permanently in the Arguments settings I do NOT enable them by default (ensure the checkbox is not ticked). That would not be a good idea and you definitely do not want to ship an application with any of these arguments set.

I talked about the core data SQLDebug argument in a previous post. From the others the one that is most useful is NSZombieEnabled which catches objects as they are being deallocated and prevents them from being freed (though you can change that). The benefit is that if an application attempts to access a deallocated object it gets logged to the console which makes it easy to track down the problem.

UICatalog[4170:207] *** -[UIDeviceRGBColor setFill]: message sent
 to deallocated instance 0x190d110

The other arguments are useful when used with Guard Malloc to track down applications that are corrupting the heap or scribbling over freed memory.

Of course the easiest way to find a memory leak these days is to use the leaks instrument but I still find it useful to have a command-line/console solution in some situations such as when running a set of unit tests.