Locating the source of a memory leak.

Daniel Williams
3 min readJan 24, 2017

--

I really enjoyed the memory leaks article by Emilien Stremsdoerfer and wanted to expand a bit on the end section. You can enable something called Malloc Stack Logging that will give the Xcode memory debugger the ability to find the exact lines of code that are causing memory leaks. This was barely touched on during a Visual Debugging WWDC session last year, and I thought I’d share it with the folks that missed it.

Enabling Malloc Stack Logging:

First you’ll need to enable Malloc Stack Logging. This is something that is enabled per scheme, so you’ll need to enable it on whichever scheme you’re using to run/debug your project. Typically you’ll want to do this on the Run scheme:

Find the scheme editor next to the ‘STOP’ button
Edit the scheme
Look for the ‘Logging’ section under your Run Scheme
Enable the Malloc Stack Logging checkbox.
Memory Debugger icon

You’ll now have an upgraded memory debugger. If you click on the visual debugger while your app is running, you can browse memory leaks like so:

This is all the same, but if you look over at the right panel you now have access to jump straight to the line causing the leak:

I must reiterate Emilien Stremsdoerfer’s point about the memory debugger being slightly misleading. In my particular case, the root of the problem ended up being a delegate from a third party framework that was lacking a weak declaration — it wasn’t listed as a leak by Xcode. However, thanks to the memory graph, I was able to track it down and submit a PR for the framework.

I also want to mention that you should turn this option on and off when you debug memory leaks. When Malloc Stack Logging is turned on, some properties aren’t logged fully when stepping through with the debugger, which can make it difficult to debug your code.

Cheers and happy debugging! 👍🏼

www.daniel-williams.co

--

--