ios - 将 UnsafeMutablePointer<UInt8> 转换为字符串时堆缓冲区溢出

标签 ios swift overflow heap-memory

我在执行以下操作时从 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/

相关文章:

ios - 在后台模式下保持 XMPP 连接作为 BLE 附件(iOS、Swift)

ios - 如何在iOS中正确处理 View Controller 中的数据持久性和状态警报

ios - 照片框架 : Connection to assetsd was interrupted or assetsd died

html - 一行放在里面溢出

html - 保持 CSS 网格中列之间的比例。 grid-column 是如何计算的?

ios - 我如何显示与附加到 UITabBarControLler 的 ViewController 不同的 ViewController

iOS - 通过代码加载导航 Controller

ios - 在应用程序重新加载之前,不会刷新用于增加 UserDefault 值的 Swift In App Purchase

swift - 尝试访问 RapidAPI yahoo Finance 通过 swift 给我错误 403

html - 溢出时不出现点