Objective-C memory leak confusion

Obviously, the following in the method mainshould lead to a leak:

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

return 0;

and clang LLVM reports a leak. However, while working through the Hillegass book, I tried to parse the following code, which again does not free the object NSMutableArray:

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

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

for (int i=0; i < 3; i++) {
    LotteryEntry *newEntry = [[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;

There was no leak this time. Am I missing something?

+3
source share
2 answers

I asked for this in the cfe-dev list, and the response to the analysis in the loops stopped at a given threshold (only 2 iterations of the loop passed).

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

0
source

, - . array 1;

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

, , .

+6

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


All Articles