memory leak when using CGImageCreateWithJPEGDataProvider

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.

  • Trouble Passing Variables to PHP Script on Image Upload
  • Getting error incorrect password on google console in firebase
  • perform segue and send tuple as sender
  • POST request with a simple string in body with Alamofire
  • ios 11 UITabBar UITabBarItem positioning issue
  • Subclassing SCNScene and SceneKit Editor
  • 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);
        ResultHolder *result = [[ResultHolder alloc] initWithCGImage:image];//sometimes memory leaks in this line.
        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]) {
            //sometimes memory leak in this line.
            mBitmap = CGImageCreateCopy(image);
            mWidth = CGImageGetWidth(image);
            mHeight = CGImageGetHeight(image);
        return self;
    - (void)dealloc {
        if (mBitmap != NULL) {
            mBitmap = NULL;

    And I release mBitmap in the dealloc.

    Thanks in advance.

    2 Solutions Collect From Internet About “memory leak when using CGImageCreateWithJPEGDataProvider”

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


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


    You should free the memory you allocated for your buffer.