【发布时间】:2019-03-25 16:46:33
【问题描述】:
在执行以下操作时,我从 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) 有关,但我没有看到我如何分配错误的内存大小,这会导致任何堆头或数据被踩踏。
更新 - 请参阅下面的答案
看起来我需要一个空终止符作为指针中的最后一个字节,否则字符串将不知道指针在哪里结束。
【问题讨论】:
标签: ios swift overflow heap-memory