My iOS app crashes with the following error: ``` m...
# kotlin-native
t
My iOS app crashes with the following error:
Copy code
malloc: *** error for object 0x280872d78: pointer being freed was not allocated
malloc: *** set a breakpoint in malloc_error_break to debug
I am guessing I am doing something wrong with my cinterop code. How can I find the cause of the issue in my code?
a
Hello! Can you share some code, please?
t
Hi @Artyom Degtyarev [JB], I am not sure what code causes the issue. Is there a proper way to debug this? This is some code I recently added (and am using it), could this be the issue?
Copy code
import kotlinx.cinterop.CPointer
import kotlinx.cinterop.addressOf
import kotlinx.cinterop.get
import kotlinx.cinterop.usePinned
import platform.Foundation.NSData
import platform.Foundation.create
import platform.posix.uint8_tVar

fun ByteArray.toNSData(): NSData = usePinned { pinned ->
    return NSData.create(
        bytesNoCopy = pinned.addressOf(0),
        length = size.toULong()
    )
}

fun NSData.toByteArray(): ByteArray {
    @Suppress("UNCHECKED_CAST")
    val bytePtr = (bytes as CPointer<uint8_tVar>)

    return ByteArray(length.toInt()) { index ->
        bytePtr[index].toByte()
    }
}
I replaced
bytesNoCopy
with
bytes
, which fixed the issue. This is probably because
NSData
with
bytesNoCopy
expects the
ByteArray
to be stable in memory, even after the create function. Is that right?
s
Sort of.