Finding memory leaks

Memory & ARC Mid-level Swift 5.0+ iOS 17+ Reviewed By Alok Singh

Order the steps

Put these steps for finding a screen leak in order.

  • Follow the retain path to the strong reference
  • Open and close the screen several times
  • Find extra instances of the screen or its view model
  • Pause in the Memory Graph debugger
  • Fix it and repeat the same steps to confirm
Hint 1 of 1

Start by reproducing the problem.

Choose an answer, then open Show answer below to check it.

Show answer

Answer: B D C A E

  1. Open and close the screen several times Repeating the action makes leaked instances pile up so they stand out.
  2. Pause in the Memory Graph debugger The graph shows every live object at that moment.
  3. Find extra instances of the screen or its view model More instances than expected means something keeps them alive.
  4. Follow the retain path to the strong reference The path shows exactly which reference to make weak.
  5. Fix it and repeat the same steps to confirm Verifying the same way proves the fix worked.

30-second answer

Start with Xcode's Memory Graph debugger: open and close a screen a few times, pause, and look for instances that should be gone; it shows the retain path keeping them alive. Use the Leaks and Allocations instruments for growth over time, and Address and Thread Sanitizers for memory corruption and data races.

Practise saying it · 45 s. No recording, just a timer

Describe your leak-hunting workflow.

Say your answer out loud, then check which of these points you covered:

  • Reproduce
  • Memory Graph
  • Retain path
  • Verify

Deep dive

Allocations 'Mark Generation' shows what survives each open-close cycle.

Enable Malloc Stack Logging to see where an object was allocated.

Memory Graph can miss leaks hidden behind unsafe pointers; Instruments complements it.

Add a deinit log in debug builds for screens and view models.

Common mistakes

  • Only looking for the Leaks instrument's red marks; abandoned memory isn't a leak to it.
  • Guessing instead of following the retain path.

Senior take & follow-ups

Seniors have a repeatable workflow and verify the fix the same way they found the leak.

Follow-up questions

Think of your answer first, then open the hint.

  1. What is abandoned memory?

    Show hint

    Memory still referenced but never used again, such as an unbounded cache.

  2. What does Thread Sanitizer catch?

    Show hint

    Data races at runtime.

Suggest a fix if something here is wrong or out of date.