I have a method where I return unsigned char *
:
- (unsigned char *)calledMethod {
...
unsigned char *result = (unsigned char*) calloc(size * 4, sizeof(unsigned char));
...
return result;
}
The problem is, when I call this method:
unsigned char *myVariable = [myClass calledMethod];
I get a memory leak.
How should I free the memory?
I've already tried free(myVariable)
, but no use. If I would call free(result)
in my calledMethod
method, there would be no leak, but then I cannot return it. Thanks in advance!
EDIT:
The problem is, I am storing in that myVariable
the pixel data of a UIImage (4 components for each CGPoint
:rgba). I have to modify some of the pixels and reconstruct the image. I am accessing the data of a point like this:
int byteIndex = (bytesPerRow * point.y) + point.x * bytesPerPixel;
CGFloat red = (myVariable[byteIndex] * 1.0) / 255.0;
CGFloat green = (myVariable[byteIndex + 1] * 1.0) / 255.0;
CGFloat blue = (myVariable[byteIndex + 2] * 1.0) / 255.0;
CGFloat alpha = (myVariable[byteIndex + 3] * 1.0) / 255.0;
If I use NSMutableData
, what would be the length
parameter in [NSMutableData dataWithBytes:(const void *) length:(NSUInteger)]
and how would I modify the data of a given CGPoint
?
free()
is the correct function to call to free up the memory. If you still have the memory leak, you are either not calling free()
at all, or you are not calling it enough. For example, the following would leak:
myVariable = [foo calledMethod];
// some stuff
myVariable = [foo calledMethod];
// more stuff
free(myVariable);
Might I suggest that, instead of using a raw buffer like this, you use an NSMutableData. That way, you'll get the benefit of whatever Objective-C memory management method you are using.
What you are doing is correct. You return an malloc-ed block of memory that you assign to myVariable
and later free it using free(myVariable)
. The code that you are showing us is not responsible for the leak. Perhaps it lies in the ...
?. What does static analysis tell you?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With