3

I'm trying to initialize Data from an UnsafeBufferPointer, but it's throwing an EXC_BAD_ACCESS when it hits the third line. Help appreciated.

let pointer = UnsafePointer<UInt8>(UnsafePointer<UInt8>(bitPattern: 15)!)
let buffer = UnsafeBufferPointer<UInt8>(start: pointer, count: 1)

let data = Data(bytes: Array(buffer)) // EXC_BAD_ACCESS

My end goal is to convert bits of data to some human readable format (eg., convert a bit pattern of 15 to "F"). I was hoping to initialize a String from the data object as a hex value. I'm open to better and correct ways of going about this.

Mark Sands
  • 1,509
  • 1
  • 14
  • 15
  • 1
    You don't need pointers for that purpose, see e.g. http://stackoverflow.com/questions/27189338/swift-native-functions-to-have-numbers-as-hex-strings. In your case: `let str = String(15, radix: 16)`. – Martin R Nov 24 '16 at 18:30
  • @MartinR thanks, but my goal isn't to get from a known value to hex. I'm reading in a file and would like to display the binary data in various formats; my example was trite. So maybe I need pointers or maybe not. Help still appreciated for my original question. – Mark Sands Nov 24 '16 at 22:32
  • Even trying `let value = buffer.map { String($0, radix: 16) }` throws an EXC_BAD_ACCESS. – Mark Sands Nov 24 '16 at 23:23
  • 1
    Your code reads the memory at the address 15 = 0xF, which most probably is not a valid address for the process. Therefore it crashes. – Martin R Nov 25 '16 at 03:40

0 Answers0