I have a C char *cArray
and it's length, and I need to convert it to NSData
I did it with:
var data: NSData? = NSData(bytesNoCopy: cArray, length: Int(length))
And it's working. The problem is that this is causing some memory leak. I don't know why, but I can see it at the allocation instruments that it's malloc 64 bytes and not freeing it when the function finish or when I set it to null.
This code been called a lot, so I need it to be leaks-free. What can I do to prevent the leak?
Edit: this is the code
func on_data_recv_fn(buf: UnsafeMutablePointer<CChar>, length: CInt, user_data: UnsafeMutablePointer<Void>) -> CInt {
guard buf != nil else {
NSLog("on_data_recv_fn buf is nil")
return -1
}
//var data: NSData? = NSData(bytesNoCopy: buf, length: Int(length), freeWhenDone: true)
var data: NSData? = NSData(bytesNoCopy: buf, length: Int(length))
let succeededWriting = Int(PacketTunnelProvider.sendPackets(data!))
data = nil
return CInt(succeededWriting)
}
According to memory instruments, there is a leak here. The sendPackets function does not holding the data so the problem isn't there.