withUnsafeBytes Data API confusion

Data(result) is using the memory allocated by result or is it
allocating again?

It’s allocating again. Should you be concerned about that? Only if you’re calling this a lot. Unless this code is very hot, that extra allocation just won’t matter.

Moreover, attempting to remove it can cause you grief. For example, the code you posted downthread has these lines:

let md = UnsafeMutablePointer<UInt8>.allocate(capacity: size)
…
return Data(bytesNoCopy: md, count: size, deallocator: .free)

which is not valid. Memory that you allocate with allocate(capacity:) must be freed by deallocate, but .free causes it to be freed by free. This happens to work on Apple platforms, but is not guaranteed by the API. For more details, see UnsafeMutablePointer allocation compatibility with C malloc/free.

Share and Enjoy

Quinn “The Eskimo!” @ DTS @ Apple

1 Like