Pointer being freed was not allocated [Swift]

三世轮回 提交于 2019-12-05 22:31:32

The problem is that the buffer is allocated only once, but free'd every time when

 String(bytesNoCopy: buffer, length: numberOfBytesRead, encoding: .ascii, freeWhenDone: true)

is called. Here is a short self-contained example demonstrating the problem:

let buffer = UnsafeMutablePointer<UInt8>.allocate(capacity: 4)
memcpy(buffer, "abcd", 4)

var s = String(bytesNoCopy: buffer, length: 4, encoding: .ascii, freeWhenDone: true)
// OK

s = String(bytesNoCopy: buffer, length: 4, encoding: .ascii, freeWhenDone: true)
// malloc: *** error for object 0x101d8dc40: pointer being freed was not allocated

Using freeWhenDone: false would be one option to solve the problem, but note that you have to free the buffer eventually.

An alternative is to use an Array (or Data) as buffer, this is automatically released when the function returns. Example:

var buffer = [UInt8](repeating: 0, count: maxReadLength)
while inputStream.hasBytesAvailable {
    let numberOfBytesRead = inputStream.read(&buffer, maxLength: maxReadLength)
    if numberOfBytesRead < 0 {
        break
    }
    if let receivedMsg = String(bytes: buffer[..<numberOfBytesRead], encoding: .ascii) {
        // ...
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!