Ivan Kramarchuk
Ivan Kramarchuk

Reputation: 236

Why does elementary Swift code cause memory leaks?

import Foundation

let path = "/Users/user/file.swift"
while (true) {
    let _ = path.components(separatedBy: "/")
}

And how can we prevent this?

The code is demo, of course.

Upvotes: 3

Views: 80

Answers (1)

Rob Napier
Rob Napier

Reputation: 299585

This code doesn't leak. It just (possibly) accumulates memory forever because you never let it be released by draining the autorelease pool. You can fix this by creating your own autorelease pool block with @autoreleasepool:

while (true) {
    @autoreleasepool {
        let _ = path.components(separatedBy: "/")
    }
}

The pool is generally drained automatically at the end of the event loop, but this code never reaches that point, so it needs to create and release its own pools.

The "(possibly)" above is because it depends on the optimizer settings and details about how components(separatedBy:) is currently implemented. In many cases the optimizer will automatically take care of the autoreleased objects.

For more on autorelease pool blocks, see Using Autorelease Pool Blocks in the Advanced Memory Management Programming Guide. For more background on Cocoa memory management (and what autorelease means), see the rest of that guide.

Upvotes: 5

Related Questions