9

I am detecting a memory leak when using string interpolation with Swift. Using the "Leaks" instrument, it shows the leaked object as a "Malloc 32 bytes", but no responsible library or frame. This seems to be caused by using optionals in string interpolation.

class MySwiftObject
{
    let boundHost:String?
    let port:UInt16

    init(boundHost: String?, port: UInt16)
    {
        if boundHost {
            self.boundHost = boundHost!
        }
        self.port = port

        // leaks
        println("Server created with host: \(self.boundHost) and port: \(self.port).")
    }
}

However, if I replace the string interpolation with simply building a String by appending pieces, no memory leak.

    // does not leak
    var message = "Server created with host: "
    if self.boundHost
    {
        message += self.boundHost!
    }
    else
    {
        message += "*"
    }
    message += " and port: \(self.port)"
    println(message)

Is there something I am doing wrong above, or just a Swift bug?

picciano
  • 22,341
  • 9
  • 69
  • 82

1 Answers1

8

Answering my own question...

It seems conditional binding is the right way to go when using string interpolation, rather than using the optionals directly. Not sure why the compiler even allows that.

Note: If someone has a better answer or better explanation, please add a new answer.

init(boundHost: String?, port: UInt16)
{
    if boundHost {
        self.boundHost = boundHost!
    }
    self.port = port

    if let constBoundHost = self.boundHost
    {
        println("Server created with host: \(constBoundHost) and port: \(self.port).")
    }
    else
    {
        println("Server created with host: * and port: \(self.port).")
    }
}
picciano
  • 22,341
  • 9
  • 69
  • 82
  • I occurred this issue too, it leaks 32 bytes in libswiftcore when I called println in a delegate callback. my solution just added "!" – PatrickSCLin Aug 13 '15 at 11:47
  • 1
    Here is a bug report for a similar problem at [bugs.swift.org](https://bugs.swift.org/browse/SR-1728) if you want to check its status. – user2067021 Aug 29 '16 at 00:56
  • Guess this is what I should have expected when I used a brand new fancy language – Allison Mar 04 '17 at 02:56