1

Here's a block of code that has leaks...

NSString *filename = [NSString stringWithFormat:@"%@.png", sketchID];
CGImageRef imageRef = CGBitmapContextCreateImage(paintView.canvas.mBitmapContext);
UIImage* image = [[UIImage alloc] initWithCGImage:imageRef];
NSData* imageData = UIImagePNGRepresentation(image); 
  1. Where are they?
  2. In general, how can I tell so I don't create leaks in the future?
  3. What's the proper way to fix them?

Thanks so much!

Maksim
  • 2,054
  • 3
  • 17
  • 33
BeachRunnerFred
  • 18,070
  • 35
  • 139
  • 238

2 Answers2

4

AS far as I can tell you have memleaks in:

CGImageRef imageRef = CGBitmapContextCreateImage(paintView.canvas.mBitmapContext);

You need to call CGContextRelease. Check this SO question out.

You need to release image aswell. After creating imageData, do:

[image release];

You don't have to release fileName since you are not explicitly allocating memory for it. It will autorelease when variable falls out of scope. There are naming conventions in objective-c that will tell you when you will have to release and when you don't. Check out Apple documentation for it.

Hope it helps.

Community
  • 1
  • 1
Pablo Santa Cruz
  • 176,835
  • 32
  • 241
  • 292
  • thanks, pablo. question, why don't i ahve to release imageData? or filename? – BeachRunnerFred Aug 19 '10 at 16:27
  • Updated the answer with a little commend on filename. You should release imageData after you are done with it. – Pablo Santa Cruz Aug 19 '10 at 16:32
  • Thanks again, Pablo. Are you sure I need to release imageData? I figured I would haven't release imageData for the same reason I don't have to release fileName. Your thoughts? – BeachRunnerFred Aug 19 '10 at 17:10
  • True. According to doc (http://developer.apple.com/iphone/library/documentation/uikit/reference/UIKitFunctionReference/Reference/reference.html#//apple_ref/c/func/UIImagePNGRepresentation) the memory will be autoreleased. – Pablo Santa Cruz Aug 19 '10 at 17:43
  • -1 You don't have to release the context; you have to release the image. – tc. Aug 19 '10 at 19:45
0

The general rule is that when you call alloc then you need a corresponding release. The exception is when you call autorelease. Also, when you use convenience methods, such as 'stringWithFormat'.

Moshe
  • 57,511
  • 78
  • 272
  • 425
  • Um, you should release. *Never* explicitly deallocate an object unless you really know what you're doing. – tc. Aug 19 '10 at 19:45