Question

I have written this piece of code:

 bitmapData = calloc(1, bitmapByteCount );
 context = CGBitmapContextCreate (bitmapData,
                                 pixelsWide,
                                 pixelsHigh,
                                 8,
                                 bitmapBytesPerRow,
                                 colorSpace,
                                 kCGImageAlphaOnly);

When I do this, is CGBitmapContext copying my bitmapData, so after these lines i should be writting

free(bitmapData); 
Was it helpful?

Solution

If you need bitmapData don't free it. If you don't need it, pass NULL as a parameter instead and Quartz will allocate memory itself (iOS 4.0 and later).

data: A pointer to the destination in memory where the drawing is to be rendered. The size of this memory block should be at least (bytesPerRow*height) bytes. In iOS 4.0 and later, and Mac OS X v10.6 and later, you can pass NULL if you want Quartz to allocate memory for the bitmap. This frees you from managing your own memory, which reduces memory leak issues.

But Quartz doesn't copy bitmapData, it does the rendering there. After you release context you should free that memory.

Edit: In one of Apple sample projects, memory is freed, but not immediately:

float drawStage3(CGContextRef context, CGRect rect)
{
    // ...
    cachedData = malloc( (((ScaledToWidth * 32) + 7) / 8) * ScaledToHeight);
    // ...
    bitmapContext = CGBitmapContextCreate(cachedData /* data */,
    // ...
    CFRelease(bitmapContext);
    // ...
    // Clean up
    CFRelease(cachedImage);
    free(cachedData);
}

OTHER TIPS

EDIT:

Your code is allocating a block of memory via calloc- you own that block of memory. So, you own freeing that memory. The CGBitmapContext create is just creating a context using the block of memory that you created (which is why you have to pass it in). When you are done with that block of memory you should free it.

I would do CFRelease on the context first. Whatever resources the context creates will be taken care of by the CFRelease.

The "Create Rule" in the Core Foundation Memory Guide Says:

Core Foundation functions have names that indicate when you own a returned object:

Object-creation functions that have “Create” embedded in the name; Object-duplication functions that have “Copy” embedded in the name. If you own an object, it is your responsibility to relinquish ownership (using CFRelease) when you have finished with it.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top