I have this code:
- (CGImageRef)createImageWithContext:(CGContextRef)context
{
return CGBitmapContextCreateImage(context);
}
- (void)fooWithContext:(CGContextRef)context
{
CGImageRef imgRef = [self createImageWithContext:context];
CGImageRelease(imgRef);
}
This is an Objective-C project building in Xcode with ARC enabled. Build and Analyze reports two errors: One on the CGBitmapContextCreateImage line identifying a potential leak, and one on the CGImageRelease noting an “Incorrect decrement of the reference count of an object that is not owned at this point by the caller”.
If I combine these two functions into one:
- (void)fooWithContext:(CGContextRef)context
{
CGImageRef imgRef = CGBitmapContextCreateImage(context);
CGImageRelease(imgRef);
}
I get no warnings.
Static code analysis bug? Or am I missing something here?
By the standard Cocoa naming conventions, a method that starts with the word
createshould return a non-owned reference. You’re returning a retained object, but you’re expected to return a non-retained object. Thus, the when the analyzer looks at-createImageWithContext:, it sees that it’s supposed to return a non-retained object, but is actually returning a retained object. Hence the first warning.In
-fooWithContext:, it looks at your code and says “Hey, according to my naming conventions,createImageWithContext:should return a non-owning reference. But then they’re releasing something they don’t own! That’s BAD!” Hence the second warning.You could fix this by changing the name of
-createImageWithContext:to something that starts withnew, such as-newImageWithContext:. Or you could annotate the method with thecf_returns_retainedmacro to indicate to the static analyzer that the method is returning an owning reference.