When I create a CGContextRef manually using CGBitmapContextCreate(), do I have to manually free the bitmap data as well?
Right now I’m doing this: I have a method that creates and returns a CGContextRef. Inside that method, I also create the data for that context, like this:
bitmapData = malloc(bitmapByteCount);
context = CGBitmapContextCreate(bitmapData, ...);
return context;
Until now I always believed that everything is just fine when the caller of this method simply releases the CGContextRef after using it: CGContextRelease(theContext);
From the documentation of CGBitmapContextCreate:
In iOS 4.0 and later, and Mac OS X
v10.6 and later, you can pass NULL if
you want Quartz to allocate memory for
the bitmap. This frees you from
managing your own memory, which
reduces memory leak issues.
This makes me think I do have to release two things after using my context which a convenience method created for me: Release the bitmap data of the context, and then the context itself.
So I must do this:
void *data = CGBitmapContextGetData(context);
if (data != NULL) {
free(data);
}
So am I having a big memory leak here if I don’t refactor all my code to release also the bitmap data, and not only the context?
Yes. You do have to eventually
free()bitmapData (once the CGContext is done drawing etc.) if youmalloc()ed it.See my (corrected) answer to your other question.
If you use the NULL option (i.e. if you do not
malloc()your bitmapData), I would expect the data pointer to be valid until youCGContextRelease()your context. So you’d either need to do whatever you want to do with the data before releasing the context, or copy the bitmap data somewhere (in which case you could just as wellmalloc()the memory beforehand and pass it to the context).