[cfe-dev] Static analyser and objc init methods

Jean-Daniel Dupas devlists at shadowlab.org
Wed Oct 29 15:37:53 PDT 2008


I think the memory leak analyser need a special semantic for objc  
class initializer methods.

Generaly, an initializer returns self, but in some case, it may decide  
to return something else (or throw an exception)
In these cases, 'self' must be release before the method returns else  
it will leaks. (http://www.cocoabuilder.com/archive/message/cocoa/2008/2/11/198549 

Additionaly, if an init method returns a new object, this object  
should be returns with a retain count to 1.

for example:

- (id)initWithString:(NSString *)str {
	if (!str) @throw [NSException  
	if (self = [super init]) {
		// do something with str
	return self;

Should detect a memory leak because when this method throws an  
exception, it does not release self.


- (id)initWithVersion:(NSInteger)aVersion {
	if (aVersion >= 10) {
		return [self init];
	} else {
		[self release];
		return [[SubClassWithOldBehavior alloc] init];

This method returns an object with retain count 1, but it is expected  
and will not cause a memory leak (actually, clang report a leak here).

More information about the cfe-dev mailing list