为什么仪器说这个代码泄漏了?

Spa*_*Dog -3 iphone instruments ipad

我有一个由Erica Sadun创建的类代码片段,仪器说它正在泄漏:

- (void)cacheBeginPointForTouches:(NSSet *)touches
{
    if ([touches count] > 0) {
        for (UITouch *touch in touches) {
            CGPoint *point = (CGPoint *)CFDictionaryGetValue(touchBeginPoints, touch);
            if (point == NULL) {
                point = (CGPoint *)malloc(sizeof(CGPoint));
                CFDictionarySetValue(touchBeginPoints, touch, point);
            }
            *point = [touch locationInView:self.superview];
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

仪器指向

 point = (CGPoint *)malloc(sizeof(CGPoint));
Run Code Online (Sandbox Code Playgroud)

作为泄漏线.

因为这个malloc的东西对我来说并不熟悉.我知道它分配内存,但由于我从未使用C,C++和其他C语言,malloc和我不是熟人.

另一个我不明白的问题是为什么她在"点"之前加上一个星号

*point = [touch locationInView:self.superview];
Run Code Online (Sandbox Code Playgroud)

那么,你是否看到代码有问题以及为什么乐器会说它在泄漏?关于星号的解释是一个奖励!:)

谢谢.

mvd*_*vds 5

规则malloc非常简单.一旦你完成了内存,应该释放它,使用free(pointer).因此,在代码中的某个时刻,字典将用于获取CGPoints.如果您的程序在此之后没有执行CGPoints(并且指针已从字典中删除),则应该调用free(point)它们.

这条线

*point = ...;
Run Code Online (Sandbox Code Playgroud)

意思是说:放入...内存中的位置,指向point.字典包含这些指向CGPoint值的指针,正如您所见,您可以轻松地首先存储指针,然后只填充指向的内存(尽管我必须承认,这不是非常直观)