3

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?

Amiram Stark
  • 2,208
  • 22
  • 32

2 Answers2

7

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)

Thomas Zoechling
  • 34,177
  • 3
  • 81
  • 112
  • i have the same problem, but when i use your code, my CGContextRef become null. i mean if i reference that object in cooler space later to release the colorspace. my context is null in that case – Gagan Joshi Aug 07 '13 at 08:24
  • 1
    Maybe you pass wrong values to CGBitmapContextCreate. This method returns NULL when context creation fails. – Thomas Zoechling Aug 07 '13 at 10:47
  • yes i checked the values for width and height both were zero that was the reason for that – Gagan Joshi Aug 13 '13 at 11:28
2

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

hamstergene
  • 24,039
  • 5
  • 57
  • 72