memory leak when using CGImageCreateWithJPEGDataPr

2019-01-29 04:17发布

I use Instruments(Leaks) to detect memory leaks of my app. It sometimes says there is a memory leak in one of my methods. I am not sure whether there is a leak and how to solve it.

CGImageCreateWithJPEGDataProvider method cause the memory leak mainly. Sometimes CGDataProviderCreateWithData also cause memory leak. But i don't know why.

The leak method in Class A is as follows:

- (ResultHolder *)decodeData:(UInt8 *) data withOffset:(int) offset {

    const int length = [IOUtilities byteArrayToIntWithData:data Offset:offset+18];
    UInt8 *buffer = malloc(length*sizeof(UInt8));
    memcpy(buffer, data+offset+22, length);

    // sometimes memory leak in this line
    CGDataProviderRef jpgDataProvider = CGDataProviderCreateWithData(NULL, buffer, length, freeData);

    // mainly memory leak in this line.
    CGImageRef image = CGImageCreateWithJPEGDataProvider(jpgDataProvider, NULL, true, kCGRenderingIntentSaturation);


    CGDataProviderRelease(jpgDataProvider);        
    ResultHolder *result = [[ResultHolder alloc] initWithCGImage:image];//sometimes memory leaks in this line.
    CGImageRelease(image);
    return result;
}

Also some other related methods:

// class A free buffer callback.
void freeData(void *info, const void *data, size_t size) {
    free((void *)data);
}
// class ReslutHolder init and dealloc.
- (id)initWithCGImage:(CGImageRef)image {
    if (self = [super init]) {
        CGImageRetain(image);

        //sometimes memory leak in this line.
        mBitmap = CGImageCreateCopy(image);

        mWidth = CGImageGetWidth(image);
        mHeight = CGImageGetHeight(image);
        CGImageRelease(image);
    }
    return self;
}

- (void)dealloc {
    if (mBitmap != NULL) {
        CGImageRelease(mBitmap);
        mBitmap = NULL;
    }
}

And I release mBitmap in the dealloc.

Thanks in advance.

2条回答
孤傲高冷的网名
2楼-- · 2019-01-29 04:48

You should free the memory you allocated for your buffer.

free(buffer);
查看更多
狗以群分
3楼-- · 2019-01-29 04:51

You can analyze the Memory Leaks in the Xcode using the analyzer as shown below

Screenshot1

Mentioning the memory leaks shown as below would help in further solving your problem

Screenshot2

查看更多
登录 后发表回答