Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CGBitmapContextCreate memory leak?

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?

like image 945
Amiram Stark Avatar asked Nov 23 '25 05:11

Amiram Stark


2 Answers

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)

like image 171
Thomas Zoechling Avatar answered Nov 24 '25 22:11

Thomas Zoechling


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

like image 41
hamstergene Avatar answered Nov 24 '25 23:11

hamstergene



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!