I have this snippet of code from a class created by Erica Sadun, that Instruments says is leaking:
- (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];
}
}
}
Instruments is pointing to
point = (CGPoint *)malloc(sizeof(CGPoint));
as the leaking line.
As this malloc stuff is not familiar to me. I know that it allocates memory, but as I never worked with C, C++ and other flavors of C, malloc and I are not acquaintances.
Another question I don’t understand is why she put an asterisk before “point” on
*point = [touch locationInView:self.superview];
So, do you see something wrong with the code and why instruments are saying it is leaking there? An explanation about the asterisk is a bonus! 🙂
thanks.
The rules for
mallocare quite simple. Once you’re done with the memory, you should free it, usingfree(pointer). So at some point in your code, the dictionary will be used to get the CGPoints. If your program does nothing after this with the CGPoints (and the pointer is removed from the dictionary), you should callfree(point)on them.The line
means to say: put
...in the location in memory, pointed to bypoint. The dictionary contains these pointers to your CGPoint values, and as you see you can easily first store the pointer, and only then fill the memory pointed to (although, I must admit, this is not very intuitive)