C / Objective-C中的Malloc 16字节泄漏

时间:2012-09-10 02:36:17

标签: objective-c c malloc free

当我使用Instruments分析我的代码时,它显示从此函数泄漏了Malloc 16字节(下面),但我从未在此函数中使用过malloc。在这个函数中是否有一个我应该释放一些资源的地方?

它可能看起来像很多代码,但我认为实际上只有变量count和count2作为可能的违规者。

+ (int) trimArray: (NSMutableArray*) source above: (short) max andMin: (short) min
{
    int counts[6][7];
    int counts2[6][7];
    for (int i=0;i<=5;i++)
    {
        for (int ii=0;ii<7;ii++)
        {
            counts[i][ii] = 0;
            counts2[i][ii] = 0;
        }
    }


    int capacity = (int)[source count]/max;
    if (capacity <2)
        capacity = 2;

    NSMutableArray *itemsToRemove = [[NSMutableArray alloc] initWithCapacity:capacity];

    int week,dow,count1,count2;
    EntryTimeItem *item;
    NSEnumerator *e;

    e = [source objectEnumerator];
    while (item = [e nextObject])
    {
        week = item.week_number;
        dow  = item.day_of_the_week;
        if (week >=0 && week <6 && dow >=0 && dow <7)
        {
            counts[week][dow]++;
        }
    }

    e = [source objectEnumerator];
    while (item = [e nextObject])
    {
        week = item.week_number;
        dow  = item.day_of_the_week;
        if (week >= 0 && week < 6 && dow >= 0 && dow < 7)
        {
            count2 = counts2[week][dow];
            count1 = counts[week][dow];
            if (count1 > max)
            {
                if (!count2)
                {
                    item.time = -1;
                    item.align = NSCenterTextAlignment;
                    item.label = [NSString stringWithFormat:@"%d entries",count1];
                }
                else {
                    // remove this item if it is after the first item which
                // was converted to a placeholder for all the items
                    [itemsToRemove addObject:item];
                }
            }
            counts2[week][dow]++;
        }
    }

    e = [itemsToRemove objectEnumerator];
    while (item = [e nextObject])
    {
        [source removeObject:item];
    }

    int count_extra_events = 0;
    for (int i=0;i<7;i++)
    {
        int count_events2 = 0;
        for (int ii = 0; ii < 6; ii++)
        {
            int count3 = counts[ii][i];
            if (count3 < max && count3 > min)
                count_events2 += count3 - min;
        }
        // store the greatest value found sofar
        if (count_events2 > count_extra_events)
        {
            count_extra_events = count_events2;
        }
    }

    return count_extra_events;
}

1 个答案:

答案 0 :(得分:6)

问题似乎源于这一行:

NSMutableArray *itemsToRemove = [[NSMutableArray alloc] initWithCapacity:capacity];

请检查是否有,可以释放资源itemsToRemove。