iPhone Memory Leaks
I have used Instruments and NSZombie for tracking application memory leaks. In this article I will use Instruments for the tracking. Instruments has the following features:
- Memory allocation (virtual memory and real memory allocation)
- Leaks in memory
- Activity Monitor
- System Trace
- Core animation
What memory leaks are and the causes of memory leaks
A memory leak is when your program loses track of a piece of memory that was allocated. The consequence is that the "leaked" memory will never be freed by the program. This usually happens when a piece of code does a "new" or a "malloc" (or an "alloc" in Objective-C) but never does a corresponding "delete", "free" or "release", respectively.
When you new, malloc, or alloc, what the OS is doing is giving your program a chunk of memory on the heap. It expects you to hold a reference to that memory address (usually in the form of a pointer) and it's relying on you to tell the OS when you're done with it (by calling free, delete, or release).
Memory leaks happen when you throw away your pointer to that memory. If your program no longer knows where in the heap your memory is allocated, how can you ever free it?
In simpler language, memory leaks mean you already freed the pointer and now the OS doesn't have a reference of that pointer.
I am creating an example application that leaks memory in two places. Blank
And there's a LeakedObject class.
Launch Instruments. Here you will see many tools in Instruments for various tasks. On the left-hand side, choose iPhone. On the right-hand menu, double-click the "Leaks" tool:
Once you've clicked that, you should see the following screen:
Please connect the device with the system. In the top-left corner of the window you'll see a drop-down menu that says "Launch Executable". Click on that and ensure that your iPhone (not your computer) is selected as the active device. Then scroll down to "Launch Executable" and you should see a list of all the apps that are installed on your iPhone. Find your app and select it.
After the app/game has run for a few seconds, the auto leak check will run and lo and behold, it will find 2 memory leaks.
Click on one memory leak. The Detail View will show you a complete stack trace to the point where your leaked memory was allocated. In our example above, clicking on the first leak reveals that a leak occurred inside [NSString initWithUTF8String]. If you look one step higher in the stack trace, you'll see the last call inside my app was to [InstrumentsTestViewController viewDidLoad].
Double-click on that line in the selected Detail View and it opens an XCode window right to the culprit!