问题
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