I Asked Claude to Create a Memory Leak in a Task and It Failed

Published: (December 3, 2025 at 02:43 AM EST)
2 min read
Source: Dev.to

Source: Dev.to

Background

Last week I asked Claude to create a memory leak in Swift’s Task API for fun. The generated code claimed that the Task captured self strongly, forming a retain cycle, and suggested using [weak self]. I knew something was off—Task does not create retain cycles by default; that’s one of its design advantages.

Investigation

To verify the claim, I examined the Swift compiler’s intermediate representation, SIL (Swift Intermediate Language). SIL shows exactly what the compiler does with your code before it becomes machine code, essentially exposing the compiler’s “notes.”

Relevant SIL excerpt

%14 = function_ref @(extension in Swift):Swift.Task.init(priority: Swift.TaskPriority?, operation: __owned @isolated(any) () async -> A) -> Swift.Task : $@convention(method)  (@in Optional, @sil_sending @owned @isolated(any) @async @callee_guaranteed @substituted  () -> @out τ_0_0 for , @thin Task.Type) -> @owned Task // user: %15
%15 = apply %14(%3, %13, %2) : $@convention(method)  (@in Optional, @sil_sending @owned @isolated(any) @async @callee_guaranteed @substituted  () -> @out τ_0_0 for , @thin Task.Type) -> @owned Task // user: %17
dealloc_stack %3 : $*Optional     // id: %16
release_value %15 : $Task            // id: %17
%18 = tuple ()                                  // user: %19
return %18 : $()                                // id: %19
} // end sil function 'MemoryLeak.LeakyViewController.startLeakyTask() -> ()'

The crucial line is:

release_value %15 : $Task

This instruction shows that the Task handle is released immediately after creation:

  • Task created
  • Task handle released immediately
  • Task not stored → no strong reference from the view controller
  • No retain cycle → no memory leak

You can read more about the release_value instruction in the Swift documentation.

Conclusion

The SIL analysis confirms that the Task does not retain the view controller, and the view controller’s deinit will be called as expected. There is no memory leak.

Sometimes the best way to understand how something works is to look at what the compiler actually does, rather than relying on assumptions. Trust, but verify—especially when working with AI‑generated code.

Back to Blog

Related posts

Read more »

The Anatomy of a macOS App

Article URL: https://eclecticlight.co/2025/12/04/the-anatomy-of-a-macos-app/ Comments URL: https://news.ycombinator.com/item?id=46181268 Points: 5 Comments: 0...

Swift #2: Tipos de datos primitivos

Tipos de datos primitivos Cada lenguaje de programación declara sus propias unidades de datos para representar valores de distintos tamaños. Estas unidades son...