0

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

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

+ (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;
}
4

1 回答 1

6

问题似乎源于以下行:

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

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

于 2012-09-10T02:38:46.093 回答