title: CGImage creates a lot of dirty memory causing the app to crash
body: <p>I try to create a UIImage by filling in my own data. So far everything works fine. But if I try to call this function several times it seems to fill the memory till the App crashes. Using the VM Tracker I found out that the dirty memory grows up to 328MB whereby 290MB is CG image memory when the app crashes.</p>
  
  <p>I call my function in a loop several times whereby ARC is enabled. The image is quite big but that shouldn't be a problem since it works fine for the 29 first iterations. As far as I know, dirty memory should be reused by the application again. Is that right? So why does it fill my memory and how can I avoid this problem?</p>
  
  <pre><code>for(int i = 0; i &lt; 1000; ++i) {
      UIImage *img = [self createDummyImage:CGSizeMake(2000, 1600)];
  }
  </code></pre>
  
  <p>Function to create dummy UIImage:</p>
  
  <pre><code>- (UIImage*)createDummyImage:(CGSize)size
  {
      unsigned char *rawData = (unsigned char*)malloc(size.width*size.height*4);
  
      // fill in rawData (logic to create checkerboard)
  
      CGColorSpaceRef colorSpaceRef = CGColorSpaceCreateDeviceRGB();
      CGBitmapInfo bitmapInfo = kCGImageAlphaNoneSkipFirst | kCGBitmapByteOrder32Host;
      CGContextRef contextRef = CGBitmapContextCreate(rawData, size.width, size.height, 8, 4*size.width, colorSpaceRef, bitmapInfo);
      CGImageRef imageRef = CGBitmapContextCreateImage(contextRef);
  
      CGColorSpaceRelease(colorSpaceRef);
      CGContextRelease(contextRef);
      free(rawData);
  
      UIImage *image = [UIImage imageWithCGImage:imageRef];
      CGImageRelease(imageRef);
  
      return image;
  }
  </code></pre>
  
  <p><strong>Working solution by hooleyhoop</strong></p>
  
  <p>Put function call into autorelease pool.</p>
  
  <pre><code>for (int i = 0; i &lt; 1000; ++i) {
      @autoreleasepool {
          UIImage *img = [self createDummyImage:CGSizeMake(2000, 1600)];
      }
  }
  </code></pre>