Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Memory leaks when using optionals in string interpolation

Tags:

ios

swift

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?

like image 296
picciano Avatar asked Jul 22 '14 21:07

picciano


People also ask

How do we avoid memory leaks in closures?

Only capture variables as unowned when you can be sure they will be in memory whenever the closure is run, not just because you don't want to work with an optional self . This will help you prevent memory leaks in Swift closures, leading to better app performance.

Can memset cause memory leak?

A memset() doesn't cause a memory leak. That just writes 0x00 bytes into part of the memory pointed to by bmi . There is not enough code here to determine whether any memory is leaked.

What is memory leak What are different types and how do you avoid them?

Memory leak occurs when programmers create a memory in heap and forget to delete it. The consequences of memory leak is that it reduces the performance of the computer by reducing the amount of available memory.

Does function create memory leak?

No it does not cause memory leaks.


1 Answers

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).")
    }
}
like image 69
picciano Avatar answered Oct 30 '22 14:10

picciano