我在执行以下操作时从地址消毒器中收到错误:
let pointer = UnsafeMutableRawPointer.allocate(byteCount: 4, alignment: 1)
pointer.storeBytes(of: 77, as: UInt8.self)
pointer.advanced(by: 1).storeBytes(of: 105, as: UInt8.self)
(pointer+2).storeBytes(of: 107, as: UInt8.self)
(pointer+3).storeBytes(of: 101, as: UInt8.self)
let typedPointer = pointer.bindMemory(to: UInt8.self, capacity: 4)
let readableData = String(cString: typedPointer)
我得到堆缓冲区溢出,但我不明白为什么。在我的实际代码中,我有一个更复杂的指针,但即使在这个简单的例子中,我也始终碰到这个问题。我认为这与String(cString:typedPointer)有关,但我不知道如何分配错误的内存大小,从而导致任何堆头或数据被阻塞。
更新-请参阅下面的答案
看起来我需要一个空结束符作为指针的最后一个字节,否则字符串将不知道指针的结束位置。
最佳答案
其他选项。。。
您可以从您的Data
创建UnsafeMutableRawPointer
:
let pointer = UnsafeMutableRawPointer.allocate(byteCount: 4, alignment: 1)
pointer.storeBytes(of: 77, as: UInt8.self)
pointer.advanced(by: 1).storeBytes(of: 105, as: UInt8.self)
(pointer+2).storeBytes(of: 107, as: UInt8.self)
(pointer+3).storeBytes(of: 101, as: UInt8.self)
let data = Data(bytes: pointer, count: 4)
let readableData = String(data: data, encoding: .utf8)
否则,
String.init(bytes:encoding:)
是另一个不声明以空结尾的序列的初始值设定项:let pointer = UnsafeMutableRawPointer.allocate(byteCount: 4, alignment: 1)
pointer.storeBytes(of: 77, as: UInt8.self)
pointer.advanced(by: 1).storeBytes(of: 105, as: UInt8.self)
(pointer+2).storeBytes(of: 107, as: UInt8.self)
(pointer+3).storeBytes(of: 101, as: UInt8.self)
let urbp = UnsafeRawBufferPointer(start: pointer, count: 4)
let readableData = String(bytes: urbp, encoding: .utf8)
请试试。