Uploaded image for project: 'Swift'
  1. Swift
  2. SR-15378

Memory leaks with Data(contentsOf:) and String.replacingOccurrences(of:with:options:range:)

    XMLWordPrintable

    Details

    • Type: Bug
    • Status: Open
    • Priority: Medium
    • Resolution: Unresolved
    • Component/s: Compiler, Foundation
    • Labels:
      None
    • Environment:

      Swift 5.5. on macOS 11.6

      Description

      The following examples need to be wrapped inside autoreleasepool / try autoreleasepool in order for the memory to be freed afterwards:

      myString.replacingOccurrences(of: "[eo]", with: "l", options: .regularExpression, range: nil)
      try Data(contentsOf: URL(fileURLWithPath: "myFile"))

      This should not be necessary. And the effect of having memory leaks when not using autoreleasepool may come as a big surprise for beginners, since autoreleasepool is not even mentioned in the Swift book.

      Furthermore, using autoreleasepool is not platform independent, and you then need to use something like the following for platform-independent code: https://github.com/apple/swift-docc/blob/38acdaddf610be6b943d82f0d9da628384784a81/Sources/SwiftDocC/Utility/FoundationExtensions/AutoreleasepoolShim.swift.

      The issue seems to be a recurring topic, see e.g.:

      Also see the discussion on https://forums.swift.org/t/the-role-of-autoreleasepool-in-swift-and-thoughts-about-memory-management-in-swift/52976.

        Attachments

          Activity

            People

            Assignee:
            Unassigned Unassigned
            Reporter:
            Stefan Springer Stefan Springer
            Votes:
            0 Vote for this issue
            Watchers:
            2 Start watching this issue

              Dates

              Created:
              Updated: