title: ECC_BAD_ACCESS while drawing an image in UIGraphicsBeginImageContextWithOptions
body: <p>I have a simple extension for <code>UIImage</code>:</p>
  
  <pre><code>func scaledWithMaxWidthOrHeightValue(value: CGFloat) -&gt; UIImage? {
  
      let width = self.size.width
      let height = self.size.height
  
      if width &lt;= value &amp;&amp; height &lt;= value {
          return self
      }
  
      let ratio = width/height
  
      var newWidth = value
      var newHeight = value
  
      if ratio &gt; 1 {
          newWidth = min(width, value)
          newHeight = height * (newWidth/width)
      } else {
          newHeight = min(height, value)
          newWidth = width * (newHeight/height)
      }
  
      UIGraphicsBeginImageContextWithOptions(CGSize(width: newWidth, height: newHeight), false, 0)
  
      draw(in: CGRect(x: 0, y: 0, width: newWidth, height: newHeight)) //Thread 11: EXC_BAD_ACCESS (code=1, address=0x28)
  
      let image = UIGraphicsGetImageFromCurrentImageContext()
      UIGraphicsEndImageContext()
  
      return image!
  }
  </code></pre>
  
  <p>What may be the reason of error?</p>
  
  <p>This method is called within <code>MagicalRecord.saveWithBlock</code> for specific <code>NSManagedObjectContext</code>:</p>
  
  <pre><code>    if let asset = record["image"] as? CKAsset {
          do {
              card!.imageData = try Data(contentsOf: asset.fileURL)
              if let imageData = card!.imageData, let image = UIImage(data: imageData) {
                  if let thumbnailImage = image.scaledWithMaxWidthOrHeightValue(value: 200) {
                      card?.thumbnailImageData = UIImagePNGRepresentation(thumbnailImage)
                  }
              }
          } catch {}
      }
  </code></pre>
  
  <p>This is output on console:</p>
  
  <pre>
  Territories(3674,0x16b90f000) malloc: *** mach_vm_map(size=983040) failed (error code=3)
  *** error: can't allocate region
  *** set a breakpoint in malloc_error_break to debug
  Territories(3674,0x16b90f000) malloc: *** mach_vm_map(size=425984) failed (error code=3)
  *** error: can't allocate region
  *** set a breakpoint in malloc_error_break to debug
  2018-07-01 21:34:07.114622+0200 Territories[3674:1366995] [Unknown process name] CGSImageDataLock: Cannot allocate memory
  </pre>