Swift:无法释放内存

Swift: Unable to deallocate memory

提问人:Rakeeb Hossain 提问时间:6/25/2019 更新时间:6/25/2019 访问量:728

问:

我正在尝试编写一种方法来调整在 Swift 中捕获的图像的大小,但是在我的函数循环(实时捕获帧)中,我在捕获几秒钟后出现错误。我意识到我没有取消分配内存,所以我添加了 defer 语句来执行此操作,但这些 defer 语句会抛出 malloc 错误,指出我没有分配内存,但我认为我已经正确分配了内存。因此,我无法解除分配的内存。

我尝试添加CVPixelBuffer(Un)LockBaseAddress语句,但这没有做任何事情。

private func resizePixelBuffer(imageBuffer: CVPixelBuffer, scaleWidth: Int, scaleHeight: Int) -> CVPixelBuffer? {
        CVPixelBufferLockBaseAddress(imageBuffer, CVPixelBufferLockFlags(rawValue: 0))
        guard let baseAddress = CVPixelBufferGetBaseAddress(imageBuffer) else {return nil}
        let bytes_per_row = CVPixelBufferGetBytesPerRow(imageBuffer)
        let width = CVPixelBufferGetWidth(imageBuffer)
        let height = CVPixelBufferGetHeight(imageBuffer)

        // Allocate input buffer
        var inBuff = vImage_Buffer(data: baseAddress, height: vImagePixelCount(height), width: vImagePixelCount(width), rowBytes: bytes_per_row)
        defer { free(inBuff.data) } // ADDED

        // Allocate output container
        let outData = UnsafeMutablePointer<UInt8>.allocate(capacity: 4*scaleWidth*scaleHeight)
        defer { outData.deallocate() } // ADDED

        // Assign output buffer
        var outBuff = vImage_Buffer(data: outData, height: vImagePixelCount(scaleHeight), width: vImagePixelCount(scaleWidth), rowBytes: 4*scaleWidth)
        defer { free(outBuff.data) } // ADDED

        let releaseCallback: CVPixelBufferReleaseBytesCallback = {_, ptr in
            if let ptr = ptr {
                free(UnsafeMutableRawPointer(mutating: ptr))
            }
        }
        // Assign output data
        let error = vImageScale_ARGB8888(&inBuff, &outBuff, nil, vImage_Flags(kvImageHighQualityResampling))
        guard error == kvImageNoError else {return nil}
        CVPixelBufferUnlockBaseAddress(imageBuffer, CVPixelBufferLockFlags(rawValue: 0))

        ...
    }

python-ios-integration(2477,0x16cf5f000) malloc: *** error for object 0x10e84c000: pointer being freed was not allocated; python-ios-integration(2477,0x16cf5f000) malloc: *** set a breakpoint in malloc_error_break to debug

斯威夫 马洛克· 西加布特

评论

0赞 haste 6/25/2019
您是否考虑过检查是否存在多次手动释放的缓冲区?这段代码中的释放对我来说看起来不错。
0赞 Rakeeb Hossain 6/25/2019
不是手动的,不行。在此事件循环中,我没有使用任何其他释放分配。但是,每次捕获帧时都会调用此函数,那么是否有可能自动释放它?不过,这并不能解释我删除解除分配时的内存泄漏......
0赞 haste 6/25/2019
我对自动释放持怀疑态度,因为在 developer.apple.com/documentation/swift/unsafemutablepointer 的文档中,指出 UnsafeMutablePointer 不提供自动内存管理。如果这不是我之前猜测的那样,我会在其他地方寻找泄漏。您是否尝试过使用内存分析器来查找一些僵尸对象或递归指针?

答: 暂无答案