我在执行以下操作时从 Address Sanitizer 收到错误消息:
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) 有关,但我没有看到我如何分配错误的内存大小,这会导致任何堆 header 或数据被踩踏。
更新 - 请参阅下面的答案
看起来我需要一个空终止符作为指针中的最后一个字节,否则 String 将不知道指针在哪里结束。
最佳答案
其他选项...
您可以从您的 UnsafeMutableRawPointer
创建Data
:
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)
请尝试。
关于ios - 将 UnsafeMutablePointer<UInt8> 转换为字符串时堆缓冲区溢出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55342692/