Pointer being freed was not allocated [Swift]

僤鯓⒐⒋嵵緔 提交于 2019-12-22 08:52:34

问题


I am trying to read long length String in TCP socket connection . For reading short length string it is working fine . but when i am trying to send long length base64 Encoded Image . it is crashing , i tried to increasing upto maxReadLength = 10000 , but still it is not working .

Reading incoming message

 private func readAvailableBytes(stream: InputStream) {
            let buffer = UnsafeMutablePointer<UInt8>.allocate(capacity: maxReadLength)

            while stream.hasBytesAvailable {
                let numberOfBytesRead = inputStream.read(buffer, maxLength: maxReadLength)

                if numberOfBytesRead < 0 {
                    if let _ = inputStream.streamError {
                        break
                    }
                }

           ❌ Crashing in  below line 👇 ❌

               if let reciviedMsg = String(bytesNoCopy: buffer,
                                         length: numberOfBytesRead,
                                         encoding: .ascii,
                                         freeWhenDone: true)
               {
                   delegate?.scoktDidRecivceNewMessagew(message: reciviedMsg)
                }

            }
        }

Error

malloc: *** error for object 0x101890c00: pointer being freed was not allocated
*** set a breakpoint in malloc_error_break to debug

回答1:


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) {
        // ...
    }
}


来源:https://stackoverflow.com/questions/52708579/pointer-being-freed-was-not-allocated-swift

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!