Andrews J
Andrews J

Reputation: 187

Memory leak in malloc showed by instruments GPUImageFilter Objective C

I'm implementing the instagram like image filters in my app and I'm using GPUImageFilters for that. But when I keep switching to different filter more than 10 times it got crashed then I tried with instruments and found out that there is a large memory allocation in GPUFilter class and its because of malloc. As I'm new to memory leak related issues, please help me out! Thanks

Here is the GPUImageFilter code:

- (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: Screenshot from instruments

Upvotes: 1

Views: 972

Answers (1)

James Bush
James Bush

Reputation: 1527

malloc doesn't free when whatever it allocates on one thread is deallocated on another.

Wrap your code in this:

dispatch_async(dispatch_get_main_queue(), ^{

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

});

Upvotes: 1

Related Questions