Question

I'm not sure I understand how to free a bitmap context.

I'm doing the following:

CGContextRef context = CGBitmapContextCreate(nil, size.width, size.height, 8, 0, CGColorSpaceCreateDeviceRGB(), kCGBitmapAlphaInfoMask);
.
. // (All straightforward code)
. 
CGContextRelease(context);

Xcode Analyze still gives me a "potential memory leak" on the CGBitmapContextCreate line.

What am I doing wrong?

Was it helpful?

Solution

As you don't assign the result of CGColorSpaceCreateDeviceRGB() to a variable, you loose reference to the object created by that method.
You need that reference later to release the colorspace object. Core Graphics follows the Core Foundation memory management rules. You can find more about that here.

Fixed version of your code:

CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
CGContextRef context = CGBitmapContextCreate(nil, size.width, size.height, 8, 0, colorSpace, kCGBitmapAlphaInfoMask);
.
. // (All straightforward code)
. 
CGContextRelease(context);
CGColorSpaceRelease(colorSpace);

If you click the blue icon that the code analyzer places in your source, you get an arrow graph that shows you the origin of the leak. (I assume it would point to the line where you create the color space)

OTHER TIPS

You are leaking the color space object from CGColorSpaceCreateDeviceRGB() call. You need to release the color space too.

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