views:

38

answers:

1

Hi,

I'm writing a create CGImageRef from a Path method. This is:

- (CGImageRef)createImage:(NSString*)path
{
    // Create NSURL
    NSURL *url = [NSURL fileURLWithPath:path];
    CFURLRef cfURL = (CFURLRef)url;

    // Create image from source
    CGImageRef image = NULL;
    CGImageSourceRef imageSource = NULL;
    imageSource = CGImageSourceCreateWithURL(cfURL, NULL);
    if(imageSource != NULL) {
        image = CGImageSourceCreateImageAtIndex(imageSource, 0, NULL);  // LEAK
        CFRelease(imageSource);
    } else {
        NSLog(@"Could not load image");
        return NULL;
    }

    // Scale Image
    if(image != NULL) {
        // Create context
        CGRect rect = CGRectMake(0.0f, 0.0f, CGImageGetWidth(image), CGImageGetHeight(image));
        CGColorSpaceRef colorSpace = CGColorSpaceCreateWithName(kCGColorSpaceGenericRGB);
        CGContextRef context = CGBitmapContextCreate(NULL, rect.size.width, 
                                                 rect.size.height, 8, 0, 
                                                 colorSpace, 
                                                 kCGImageAlphaPremultipliedFirst);
        CGContextSetInterpolationQuality(context, kCGInterpolationHigh);
        CGContextDrawImage(context, rect, image);   // LEAK
        CGContextFlush(context);
        CGColorSpaceRelease(colorSpace);
        CGImageRelease (image);

        // Create scaledImage
    scaledImage = CGBitmapContextCreateImage(context);  // LEAK
    image = scaledImage;
    CGContextRelease (context);
    }

    return image;
    }   

I have turn on Garbage Collector. When I use Instrument, I find leak in CGImageSourceCreateImageAtIndex, CGContextDrawImage and CGBitmapContextCreateImage. Where are the error please? How I should manage the memory in Core Graphics When I turn on Garbage Collector? Thank you and excuse my english.

A: 

The leak is probably happening because you're not releasing the CGImageRef returned from the method.

Dave DeLong
Thank Dave. I release the CGImageRef returned. The leak appear in the createImage Method.
Fernando
@Fernando the Leaks tool shows where the leaked memory was created, not where it was lost. In other words, it shows you *what* was leaked, not *where* it was leaked.
Dave DeLong
If a click in right button (View Buttons), I can look stack trace. http://cl.ly/ebef2544db1817189bc1 In this stack trace I look something wrong in my createImage method: http://cl.ly/60c121f7e38ea92431bb
Fernando
Fernando: That doesn't contradict what Dave said. That's the stack trace for the allocation of that memory. Go into the object history for the address to see all allocation, retention, release, autorelease, and deallocation events for it. You might also try using the Object Graph instrument to see what might be holding onto the memory (although I don't know whether Object Graph works on bare memory buffers or only Obj-C/CF objects).
Peter Hosey