Clang error on "Potential Zero Dereferencing".

I keep getting Clang errors in the following type of code, and I can't figure out why they are wrong or how to solve them to satisfy Clang:

+ (NSString *)checkForLength: (NSString *)theString error: (NSError **)error { BOOL hasLength = ([theString length] > 0); if (hasLength) return theString; else { *error = [NSError errorWithDomain:@"ErrorDomain" code:hasLength userInfo:nil]; return nil; } } 

Leaving aside the completely far-fetched nature of the example (which Klang made so that it was illustrative enough), Klang refuses the error assignment line with the following objection:

Potential zero dereferencing. According to coding standards, in the section "Creating and returning NSError objects", the parameter "error" can be zero.

I like to have a clean Clang report. I read the cited document, and I see no way to do what was expected; I checked out some Cocoa open source libraries and this seems to be a common idiom. Any ideas?

+46
cocoa clang-static-analyzer
Jul 27 '09 at 17:28
source share
2 answers

How to do what is expected is shown in listing 3-5 in this document. With your sample code:

 + (NSString *)checkForLength: (NSString *)theString error: (NSError **)error { BOOL hasLength = ([theString length] > 0); if (hasLength) return theString; else { if (error != NULL) *error = [NSError errorWithDomain:@"ErrorDomain" code:hasLength userInfo:nil]; return nil; } } 
+95
Jul 27 '09 at 17:36
source share

Cocoa's convention is that the return value should indicate success or failure (in this case you return nil for failure), and the error is filled with additional information, but only when the caller requests it.

In other words

 NSError *error = nil; NSString *result = [self checkForLength: aString error: &error]; 

and

 NSString *result = [self checkForLength: aString error: NULL]; 

are valid ways to call a method. Therefore, the body of the method should always check for the NULL error parameter:

 if (error != NULL) *error = ...; 
+16
Jul 27 '09 at 17:44
source share



All Articles