Bug 38853 - Potential memory leak with UIGraphics.GetImageFromCurrentImageContext
Summary: Potential memory leak with UIGraphics.GetImageFromCurrentImageContext
Alias: None
Product: iOS
Classification: Xamarin
Component: Xamarin.iOS.dll ()
Version: XI 9.4 (iOS 9.2)
Hardware: PC Mac OS
: Normal normal
Target Milestone: Untriaged
Assignee: Manuel de la Peña [MSFT]
Depends on:
Reported: 2016-02-17 16:53 UTC by Adam Hartley [MSFT]
Modified: 2016-03-07 12:16 UTC (History)
5 users (show)

Is this bug a regression?: ---
Last known good build:

Notice (2018-05-24): bugzilla.xamarin.com is now in read-only mode.

Please join us on Visual Studio Developer Community and in the Xamarin and Mono organizations on GitHub to continue tracking issues. Bugzilla will remain available for reference in read-only mode. We will continue to work on open Bugzilla bugs, copy them to the new locations as needed for follow-up, and add the new items under Related Links.

Our sincere thanks to everyone who has contributed on this bug tracker over the years. Thanks also for your understanding as we make these adjustments and improvements for the future.

Please create a new report on Developer Community or GitHub with your current version information, steps to reproduce, and relevant error messages or log files if you are hitting an issue that looks similar to this resolved bug and you do not yet see a matching new report.

Related Links:

Description Adam Hartley [MSFT] 2016-02-17 16:53:53 UTC
## Steps to reproduce

1. Download and run the sample project - either the simulator or device will work
2. Profile the allocations with Instruments
3. Drag over the image to erase and continue while observing memory usage / pressure

## Expected result

No leak

## Actual result

Memory is leaking causing high usage. Location of leak appears to be at line 208 of DocumentView.cs:

using (var img = UIGraphics.GetImageFromCurrentImageContext ()) {
    imageView.Image = null;
    imageView.Image = img;

## Notes

=== Xamarin Studio ===

Version 5.10.2 (build 56)
Installation UUID: 11a26d86-0d21-407a-8da9-8c197ecc0ad1
	Mono 4.2.2 (explicit/996df3c)
	GTK+ 2.24.23 (Raleigh theme)

	Package version: 402020030

=== Xamarin.Profiler ===

Version: 0.31.0
Location: /Applications/Xamarin Profiler.app/Contents/MacOS/Xamarin Profiler

=== Apple Developer Tools ===

Xcode 7.2.1 (9548.1)
Build 7C1002

=== Xamarin.iOS ===

Version: (Business Edition)
Hash: 962a050
Branch: master
Build date: 2016-01-29 16:59:11-0500

=== Xamarin.Android ===

Version: (Business Edition)
Android SDK: /Users/Adam/Library/Developer/Xamarin/android-sdk-macosx
	Supported Android versions:
		4.0.3 (API level 15)
		4.4   (API level 19)
		5.0   (API level 21)
		5.1   (API level 22)
		6.0   (API level 23)

SDK Tools Version: 24.4.1
SDK Platform Tools Version: 23.1
SDK Build Tools Version: 23.0.1

Java SDK: /usr
java version "1.8.0_73"
Java(TM) SE Runtime Environment (build 1.8.0_73-b02)
Java HotSpot(TM) 64-Bit Server VM (build 25.73-b02, mixed mode)

=== Xamarin Android Player ===

Not Installed

=== Xamarin.Mac ===

Version: (Business Edition)

=== Build Information ===

Release ID: 510020056
Git revision: bb74ff467c62ded42b7b7ac7fdd2edc60f8647b0
Build date: 2016-01-26 16:24:41-05
Xamarin addins: 8b797d7ba24d5abab226c2cf9fda77f666263f1b
Build lane: monodevelop-lion-cycle6-c6sr1

=== Operating System ===

Mac OS X 10.11.3
Darwin Adams-Retina-MacBook-Pro.local 15.3.0 Darwin Kernel Version 15.3.0
    Thu Dec 10 18:40:58 PST 2015
    root:xnu-3248.30.4~1/RELEASE_X86_64 x86_64
Comment 2 Sebastien Pouliot 2016-02-18 18:50:23 UTC
@Manuel can you (a) confirm the leak and (b) minimize the test case ?
Comment 3 Manuel de la Peña [MSFT] 2016-02-29 11:11:28 UTC
This is a user error due to the code used to draw the path onto the image. The situation is a follows:

within DocumentView.cs we have:

using (var img = UIGraphics.GetImageFromCurrentImageContext ()) {
	imageView.Image = null;
	imageView.Image = img;

In the above code, when setting Image to null on the UIImageView, the ref count of the image is decreased but the memory will not be collected until the next call to the GC. Due to the fact that the implementation of the drawing is not correct, the images are updated in every update of the position, this means that we get a memory warning quite quickly and the memory is collected. If the drawing logic was correct, we could simply do the following:

using (var img = UIGraphics.GetImageFromCurrentImageContext ()) {
        var old = imageView.Image;
	imageView.Image = null; // reduce ref count
	imageView.Image = img;
        if (old != null)
            old.Dispose ();

Unfortunately, and as I mentioned before, the way the drawing is performed is incorrect and doing my code example (calling dispose in the not longer needed image) means that the code does not work as expected.

I recommend the following approach:

1. Create a class that extends the UIView class.
2. Add properties for Lastpoint and CurrentPoint. The current point property should call SetNeedsDisplay to ensure that the view will be redrawn in the next cycle.
3. Override the draw method (public void Draw (CGRect rect)) to first draw the image on the rectangle and on top of it the different paths.

Following the above guidelines we will only need to have a single ref to the image to be drawn, not needing to create a new image in every draw cycle, not needed to dispose the old image and also fixing the mem leak.

Besides the above, and for this example, it is a better approach to use bézier paths rather than CGPath.
Comment 4 Manuel de la Peña [MSFT] 2016-02-29 11:41:01 UTC
Taking a look at https://developer.xamarin.com/samples/monotouch/PaintCode/ might be a good starting point on how to use the bezier paths. The extra step would be to first draw the image on the desired rect.
Comment 5 Slava 2016-03-07 12:16:56 UTC
Thanks guys

I have implemented the suggested changes with some additional improvements and all works super great.