Build and analyze false positives when a leak is detected?

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 project in Xcode with ARC enabled. Build and analyze two errors: one on the CGBitmapContextCreateImage line that identifies the potential leak, and one on CGImageRelease, noting "incorrect decrement count of the object that is not currently owned by the caller."

If I combine these two functions into one:

 - (void)fooWithContext:(CGContextRef)context { CGImageRef imgRef = CGBitmapContextCreateImage(context); CGImageRelease(imgRef); } 

I do not receive any warnings.

Error parsing static code? Or am I missing something here?

+4
source share
2 answers

According to Cocoa’s standard naming conventions, a method starting with create must return a non-country link. You are returning a saved object, but you are expecting to return an unsaved object. Thus, when the parser looks at -createImageWithContext: it sees that it should return an -createImageWithContext: object, but actually return the stored object. Hence the first warning.

In -fooWithContext: he looks at your code and says: "Hey, according to my naming conventions, createImageWithContext: should return a non-owner link, but then they release what they don’t have !!" Hence the second warning.

You can fix this by changing the name -createImageWithContext: to something that starts with new , for example, -newImageWithContext: Or you could annotate the method using the cf_returns_retained macro to tell the static analyzer that the method returns a reference to the owner.

+8
source

I would suggest that this is a “false positive” that really makes sense:

The analyzer does not know that the return value in createImageWithContext: must be released (you could call createImageWithContext: somewhere else where you do not do CGImageRelease ), and it does not know that imgRef in fooWithContext: stored correctly.

My 2 cents :)

0
source

Source: https://habr.com/ru/post/1385431/


All Articles