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?
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.
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.
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.
No it does not cause memory leaks.
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).")
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With