通过仪器GPUImageFilter目标C显示malloc中的内存泄漏

时间:2014-03-14 06:19:46

标签: ios objective-c memory-management malloc instruments

我在我的应用中实现了类似图片过滤器的Instagram,并且我正在使用GPUImageFilters。但是当我不断切换到不同的过滤器10次以上时,它就崩溃了,然后我尝试使用仪器,发现GPUFilter类中存在大量的内存分配,因为malloc。由于我是内存泄漏相关问题的新手,请帮帮我!感谢

这是GPUImageFilter代码:

- (UIImage *)imageFromCurrentlyProcessedOutput {
    [GPUImageOpenGLESContext useImageProcessingContext];
    [self setFilterFBO];

    CGSize currentFBOSize = [self sizeOfFBO];

    NSUInteger totalBytesForImage = (int)currentFBOSize.width * (int)currentFBOSize.height * 4;
    GLubyte *rawImagePixels = (GLubyte *)malloc(totalBytesForImage); //here its showing the large memory allocation
    glReadPixels(0, 0, (int)currentFBOSize.width, (int)currentFBOSize.height, GL_RGBA, GL_UNSIGNED_BYTE, rawImagePixels);

    CGDataProviderRef dataProvider = CGDataProviderCreateWithData(NULL, rawImagePixels, totalBytesForImage, dataProviderReleaseCallback);


    CGColorSpaceRef defaultRGBColorSpace = CGColorSpaceCreateDeviceRGB();

    CGImageRef cgImageFromBytes = CGImageCreate((int)currentFBOSize.width, (int)currentFBOSize.height, 8, 32, 4 * (int)currentFBOSize.width, defaultRGBColorSpace, kCGBitmapByteOrderDefault, dataProvider, NULL, NO, kCGRenderingIntentDefault);
    UIImage *finalImage = [UIImage imageWithCGImage:cgImageFromBytes scale:1.0 orientation:UIImageOrientationUp];



    // free(rawImagePixels);
    CGImageRelease(cgImageFromBytes);
    CGDataProviderRelease(dataProvider);
    CGColorSpaceRelease(defaultRGBColorSpace);


    return finalImage; 
}

乐器截图: Screenshot from instruments

1 个答案:

答案 0 :(得分:1)

当在一个线程上分配的内容在另一个线程上释放时,malloc不会释放。

将代码包装在此:

dispatch_async(dispatch_get_main_queue(),^ {

// malloc and whatever other code goes here...

});