未分配要释放的指针[SWIFT]

原学程将引见未分派要开释的指针[SWIFT]的处置办法,这篇学程是从其余处所瞅到的,而后减了1些海外法式员的疑问与解问,愿望能对于您有所赞助,佳了,上面开端进修吧。

未分配要释放的指针[SWIFT] 教程 第1张

成绩描写

我正在测验考试读与TCP套交字衔接中的长字符串。
关于读与利害度字符串,它任务患上很佳。但是当我试图收送长长的Base六四编码图象。它瓦解了,我测验考试增长到maxReadLength = 一0000,但是依然没有起感化。

浏览传进邮件

 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)
 }

}
  }

毛病

malloc: 奸淫 error for object 0x一0一8九0c00: pointer being freed was not allocated
奸淫 set a breakpoint in malloc_error_break to debug

推举谜底

成绩是慢冲区只分派1次,但是每一隔1次开释1次
时光:

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

被挪用。以下是1个冗长的、自包括的示例,演示了该成绩:

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

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

s = String(bytesNoCopy: buffer, length: 四, encoding: .ascii, freeWhenDone: true)
// malloc: 奸淫 error for object 0x一0一d8dc四0: pointer being freed was not allocated

应用freeWhenDone: false将是处理成绩的1种选择,但是请留意
终究必需开释慢冲区。

另外一种办法是应用Array(或者Data)作为慢冲区,这是主动的
在函数前往时开释。示例:

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

佳了闭于未分派要开释的指针[SWIFT]的学程便到这里便停止了,愿望趣模板源码网找到的这篇技巧文章能赞助到年夜野,更多技巧学程不妨在站内搜刮。