ios - CGContextDrawImage (Swift) 上的间歇性 "incorrect checksum for freed object"错误

标签 ios swift cgcontext

我的应用程序确实遇到过一次罕见的崩溃 - 在我将 UIImage 转换为像素数组以便我可以一个一个地处理像素的方法中时不时发生(它是一个着色书应用程序)。

我的转换代码如下

init(image: UIImage){
    let imageref = image.CGImage
    self.width = CGImageGetWidth(imageref)
    self.height = CGImageGetHeight(imageref)
    // create new bitmap context
    let bitsPerComponent = UInt(8)
    let bytesPerPixel = UInt(4)
    let bitsPerPixel = bitsPerComponent * bytesPerPixel
    let bytesPerRow = UInt(self.width * bytesPerPixel)
    let byteCount = UInt(bytesPerRow * self.height)
    let colorSpace = CGColorSpaceCreateDeviceRGB()
    let bitmapInfo: CGBitmapInfo = CGBitmapInfo(rawValue: CGImageAlphaInfo.PremultipliedFirst.rawValue)
    let context = CGBitmapContextCreate(nil, self.width, self.height, bitsPerComponent, bytesPerRow, colorSpace, bitmapInfo)

    // draw image to context
    let rect = CGRectMake(0, 0, CGFloat(self.width), CGFloat(self.height))
    CGContextDrawImage(context, rect, imageref)
    // manipulate binary data
    let tmpPixelsArray: UnsafeMutablePointer<ARGB> = UnsafeMutablePointer<ARGB>(CGBitmapContextGetData(context))
    self.pixels = UnsafeMutablePointer<ARGB>.alloc(Int(byteCount));
}

崩溃发生在

        CGContextDrawImage(context, rect, imageref)

行,错误消息为“malloc:对象 0x7aa3b000 的 *** 错误:释放对象的校验和不正确 - 对象可能在释放后被修改。”

没有通用的复制模式。有时它发生在第 10 次迭代,有时发生在第 5 次,有时发生在第 20 次。知道如何进一步调试吗?

最佳答案

问题 #1 是每次都创建 self.pixels 表。我现在把它放在检查当前数组大小的后面。

问题 #2 是缺少此数组的内存管理(销毁和释放)。

修复了一段代码 - 而不是:

self.pixels = UnsafeMutablePointer<ARGB>.alloc(Int(byteCount));

我现在有:

if (byteCount>self.previousMaxByteCount){
        println("ALLOC: \(byteCount)")
        self.previousMaxByteCount = byteCount
        self.pixels.destroy()
        self.pixels.dealloc(1)
        self.pixels = nil
        self.pixels = UnsafeMutablePointer<ARGB>.alloc(Int(byteCount));
    }

我还了解到,Swift/Xcode 报告的崩溃位置并不像我以前的 Java 经验那样可靠,问题也不完全在最初指出的行中。

关于ios - CGContextDrawImage (Swift) 上的间歇性 "incorrect checksum for freed object"错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28412219/

相关文章:

iphone - Objective-C : Is there a way to call class methods on a class object without compiler complaints?

ios - 无法使用类型 'Range<_>' 的参数列表调用类型 '(Range<String.Index>)' 的初始值设定项

iphone - 上下文绘图+分页

ios - 无法创建 PDF 和打印超过 60 页(内存升高和崩溃)

ios - CLGeocoder 如何设置超时?

ios - UITableViewCell 上的动画

macos - 如何从 swift 访问 iokit/pwr_mgt?

iOS : Repositioning UIGraphicsBeginImageContext and UIImageView

ios - 在子字符串中拆分 NSString

ios - EKEventStore requestAccess() 无法在 iOS 9 中显示用户提示