Domanda

The static analyzer is informing me that the following code has a potential leak. I don't understand how there's any room for a leak. Further, I don't understand how the analyzer can be so helpful across the entire project yet miss something this easy.

My assumption is that the analyzer is right and I am leaking. But how?

+ (McFieldDefinition *) freeformFieldDefinition {
    return [[[McFieldDefinition alloc] initWithText:@"0201FFM100"] autorelease];
}

Thanks!

È stato utile?

Soluzione

Sorry for posting this question. I finally found an answer here: https://stackoverflow.com/a/15668026/300986.

The problem was in my init method:

- (id) initWithText:(NSString *)text {
    if (!text) return nil;
    if ([text length] < 7) return nil;
    self = [self init];
    if (self) {
        // do stuff
    }
    return self;
}

Those two guard clauses return nil if I don't like the text variable. self is already alloc'ed by that point, so it's Analyzer 1, bmauter 0.

Here's my new version:

- (id) initWithText:(NSString *)text {
    self = [self init];
    if (!self) return nil;

    if (!text || [text length] < 7) {
        [self release];
        return nil;
    }

    // do stuff

    return self;
}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top