开发者

Objective-C memory leak confusion

开发者 https://www.devze.com 2022-12-14 23:54 出处:网络
Obviously the following in the main method should lead to a leak: NSMutableArray *strings = [[NSMutableArray alloc] init];

Obviously the following in the main method should lead to a leak:

NSMutableArray *strings = [[NSMutableArray alloc] init];
[strings addObject:@"Hello"];
[strings addObject:@"Howdy"];

return 0;

and the clang LLVM reports the leak. However, working through the Hillegass book, I tried analyzing the following code, which again does not release the NSMutableArray object:

NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];

NSMutableArray *array = [[NSMutableArray alloc] init];
NSCalendarDate *now = [[NSCalendarDate alloc] init];

for (int i=0; i < 3; i++) {
    LotteryEntry *newEntr开发者_JAVA百科y = [[LotteryEntry alloc] init];
    NSCalendarDate *iweeksFromNow = [now dateByAddingYears:0
                                                    months:0
                                                      days:(i*7)
                                                     hours:0
                                                   minutes:0 
                                                   seconds:0];
    [newEntry setEntryDate:iweeksFromNow];
    [array addObject:newEntry];
    [newEntry release];
}

[now release];

for (LotteryEntry *entry in array) {
    NSLog(@"%@", entry);
}


[pool drain];
return 0;

This time there was no leak reported. Am I missing something obvious?


I don't think you are—the static analyzer's just missing it. array does end with a retain count of 1; if the line were

 NSMutableArray *array = [[[NSMutableArray alloc] init] autorelease];

then the enclosing autorelease pool would take care of it, but as it stands the array's definitely still leaking.


I've asked this on the cfe-dev list and the answer is analysis in loops is halted at a given threshold (only 2 loop iterations are walked through).

If you change your exit condition (for (int i=0; i < 2; i++)) the static analyzer will signal the leak.

0

精彩评论

暂无评论...
验证码 换一张
取 消