What causes a memory leak?

What causes a leak in this code? I really can't understand it. On these lines: 1: NSMutableArray * days = [[NSMutableArray alloc] init]; 2: [dic setObject: days forKey: key]; 3: [days addObject: value];

The whole method:

-(void) addValueToDictionary: (NSMutableDictionary *) dic withValue: (NSNumber *) value forKey: (NSString *) key {
NSMutableArray * days =  [dic objectForKey:key];
if (days == nil) {
    NSMutableArray * days = [[NSMutableArray alloc]init];
    [days addObject:value];
    [dic setObject:days forKey:key];
    [days release];
    days = nil;
}
else {
    [days addObject:value];
}

}

BR // Kristoffer

+3
source share
5 answers

Check if dic is freed. You must NSLog keepCount earlier than you think the final versions, and make sure they are 1 immediately before the final version.

, , , . Build and Analyze , scan-build , scan-build Xcode.

Xcode Clang

+1

days. , . . .

-(void) addValueToDictionary: (NSMutableDictionary *) dic withValue: (NSNumber *) value forKey: (NSString *) key 
{
    if (nil == dic || nil == key || nil == value) return; // bail out on nil parameters 
    if (![dic objectForKey:key]) {
        NSMutableArray * days = [[NSMutableArray alloc] init];
        [dic setObject:days forKey:key];
        [days release];
    }
    [[dic objectForKey:key] addObject:value];
}
+1

NSMutableArray * if? - ?

0

There is nothing wrong with this particular piece of code (except for the slightly dubious redefinition of days in the inner area). Somewhere else you save, but forget to free the object that you put in the dictionary.

0
source

change the initialization of NSMutableArray to ...

NSMutableArray * days = [NSMutableArray array];
0
source

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


All Articles