Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 301
Ivan Kramarchuk Avatar asked May 12 '26 11:05

Ivan Kramarchuk


1 Answers

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.

like image 71
Rob Napier Avatar answered May 18 '26 05:05

Rob Napier



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!