Friday, February 18, 2011

How to detect memory leaks in OS X Applications

In this tutorial I am going to demonstrate how to detect memory leaks in your OS X applications. We are going to use XCode development environment and Instruments tool that comes with XCode.

1.  Put a break point at the end of your application. In this example we have a simple application called Prog1 which we set to deliberately leak memory. Note the commented out line that would cause a 16 byte memory leak:

//[aFraction release]:

Cick to enlarge
2. Run the application in Debug mode and let it stop at the breakpoint.

3. Meanwhile locate the tool called Instruments under Developer/Applications and run it.

4. Select the template called Leaks and press Choose.

Click to enlarge

5. This will bring up a panel with Allocations and Leaks Instruments.

6. Select Leaks instrument by clicking on it.

Click to enlarge

7. Click Target selector on top left and choose the option Attach to Process.

8. From the drop down menu of running processes choose your application by name (eg. Prog1)

9. Press the red Record button on top left. This will start a memory leak detection session.

10. When leaked objects are listed press the red button again to stop.

11. The first line reporting 128 bytes leak is a false alarm it has nothing to do with your application. All Cocoa applications leak 128 bytes. Some argue this is an Apple bug that needs to be fixed.

12. The rest in the listing are your applications' memory leaks. The neat thing is your leaked object's type is given, in this case the class Fraction and how much it leaked.

No comments:

Post a Comment

iTerm2 - How to auto-close sessions and auto-exit when last one closed

 Problem There are two problems when you close sessions and windows in ITerm2. When you gracefully exit from ITerm2 sessions with a recommen...