Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

objc leak behavior I can't explain

The following code loop does not leak memory (as verified by watching it loop infinitely under "top");

NSBitmapImageRep *this_bmap = 0;

while (1) {

  CGImageRef windowImage = 
     CGWindowListCreateImage(CGRectNull,
                             kCGWindowListOptionIncludingWindow,
                             windowID, kCGWindowImageDefault);

  this_bmap = [[NSBitmapImageRep alloc] initWithCGImage:windowImage];

  [this_bmap release];
  CGImageRelease(windowImage);
}

and I would not expect it to. However, when I copy a pointer to the bitmap data, like this:

NSBitmapImageRep *this_bmap = 0;

while (1) {

  CGImageRef windowImage = 
     CGWindowListCreateImage(CGRectNull,
                             kCGWindowListOptionIncludingWindow,
                             windowID, kCGWindowImageDefault);

  this_bmap = [[NSBitmapImageRep alloc] initWithCGImage:windowImage];

  void *pixels1 = [this_bmap bitmapData];

  [this_bmap release];
  CGImageRelease(windowImage);
}

this now leaks like crazy. I can see this happening rapidly under "top" and the program eventually grinds to a halt.

I am new to Objective-C, but I am not new to programming and I can't understand this behavior. The documentation for the method bitmapData claims it simply returns a pointer (as opposed to allocating something), so I am stumped. I found a similar question from some time ago, but the only answer was to "look into pools" and I don't see how that could help here.

Any ideas what's going on here?

like image 315
rwa Avatar asked May 03 '26 05:05

rwa


1 Answers

Accessing the pixel data causes the object to be retained and autoreleased so that the bitmap data doesn't suddenly go away unexpectedly. To see your expected results (i.e., loop not consuming memory with each iteration), rewrite as:

NSBitmapImageRep *this_bmap = 0;

while (1) {
  NSAutoreleasePool* loopPool = [NSAutoreleasePool new];
  CGImageRef windowImage = 
     CGWindowListCreateImage(CGRectNull,
                             kCGWindowListOptionIncludingWindow,
                             windowID, kCGWindowImageDefault);

  this_bmap = [[NSBitmapImageRep alloc] initWithCGImage:windowImage];

  void *pixels1 = [this_bmap bitmapData];

  [this_bmap release];
  CGImageRelease(windowImage);
  [loopPool drain];
}
like image 181
Jason Coco Avatar answered May 06 '26 01:05

Jason Coco



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!