Mavro
Mavro

Reputation: 571

Initialization of 'UnsafePointer<UInt8>' results in a dangling pointer

Trying to clean up some warnings in my SWIFT 5/XCODE project and I'm stuck on this one:

 let sendBytes:[UInt8] = [0x0, 0x0, 0x5, 0x0]
 let msgData = Data(bytes: UnsafePointer<UInt8>(sendBytes), count: sendBytes.count)
 socket.write(msgData, withTimeout: -1.0, tag: 0)
 socket.readData(withTimeout: -1.0, tag: 0)
        

For the "UnsafePointer" I'm getting the following warning and two suggestions:

Initialization of 'UnsafePointer' results in a dangling pointer

  1. Implicit argument conversion from '[UInt8]' to 'UnsafePointer' produces a pointer valid only for the duration of the call to 'init(_:)'

  2. Use the 'withUnsafeBufferPointer' method on Array in order to explicitly convert argument to buffer pointer valid for a defined scope

This is my solution, better?

Version 1:

let sendBytes:[UInt8] = [0x0, 0x0, 0x5, 0x0]
let uint8Pointer = UnsafeMutablePointer<UInt8>.allocate(capacity: sendBytes.count)
uint8Pointer.initialize(from: sendBytes, count: sendBytes.count)
let msgData = Data(bytes: uint8Pointer, count: sendBytes.count)
socket.write(msgData, withTimeout: -1.0, tag: 0)
socket.readData(withTimeout: -1.0, tag: 0)

Version 2:

let sendBytes:[UInt8] = [0x0, 0x0, 0x5, 0x0]                     
let uint8Pointer = UnsafeMutablePointer<UInt8>.allocate(capacity: sendBytes.count)
uint8Pointer.initialize(from: sendBytes, count: sendBytes.count)
let msgData = Data(bytes: uint8Pointer, count: sendBytes.count)
socket.write(msgData, withTimeout: -1.0, tag: 0)
socket.readData(withTimeout: -1.0, tag: 0)
uint8Pointer.deallocate()

Upvotes: 2

Views: 2261

Answers (1)

vadian
vadian

Reputation: 285260

Since Swift 3 it's possible to simply initialize a Data instance with an UInt8 array.

let sendBytes:[UInt8] = [0x0, 0x0, 0x5, 0x0]
let msgData = Data(sendBytes)

Upvotes: 7

Related Questions