Reputation: 4287
Below is some core graphics code..
CGColorRef colorRefArray[MAGIC_NUM];
for (int i = 0; i < MAGIC_NUM ; i++)
{
...
colorRefArray[i] = CreateColor(colorValueForEachColor, numberofcomp);
}
colorRefArray already has memory and CreateColor(); will again create a memory and it leads to memory leak.
How do I avoid this situation?
One possible thought I have is
CGColorRef colorRefArray[MAGIC_NUM];
for (int i = 0; i < MAGIC_NUM ; i++)
{
...
CGColorRef colorref = CreateColor(colorValueForEachColor, numberofcomp);
colorRefArray[i] = colorref;
CFRelease(colorref);
}
Is this approach correct?
Upvotes: 1
Views: 162
Reputation: 43472
No, because then colorRefArray
will be filled with invalid pointers.
Try using a CFMutableArray
instead of a raw C array. Then you only have to worry about the reference to the array, as it will own the colours for you:
CFArrayRef CopyColorArray(void) {
CFMutableArrayRef colorRefArray = CFArrayCreateMutable(NULL, 0, &kCFTypeArrayCallBacks);
if (colorRefArray) {
for (int i = 0; i < MAGIC_NUM ; i++) {
...
CGColorRef colorref = CreateColor(colorValueForEachColor, numberofcomp);
if (colorref) {
CFArrayAppendValue(colorRefArray, colorref);
CFRelease(colorref);
}
}
}
return colorRefArray;
}
Upvotes: 2
Reputation: 133092
No it's not. You're immediately releasing the color you created. The correct approach would be this:
CGColorRef colorRefArray[MAGIC_NUM];
for (int i = 0; i < MAGIC_NUM ; i++)
{
...
colorRefArray[i] = CreateColor(colorValueForEachColor, numberofcomp);
}
//Use your colors
//Now release them
for (int i = 0; i < MAGIC_NUM ; i++)
{
CFRelease(colorRefArray[i]);
}
Upvotes: 2