简体   繁体   中英

Memory leak with unsigned char *

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?

Calling free when you are done will deallocate the memory. Are you sure you instrumented things correctly when you tried calling free(myVariable) ? That should work.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM