Closure with captured array will cause memory leak


(James Esword) #1

IDE: VS 2015
Version: 8.3.94.2001
Target (If relevant): iOS + C#
Description:

As below code, if an array is captured by a closure, the array and its elements will be leaked under ARC, even after all visible strong references are removed as you can.

IOSApp1.zip (106.9 KB)

public delegate void Action();

public class TestClass {

    private readonly String mTag;

    public TestClass(String tag) {
        mTag = tag;
    }

    public void test() {
    }

    public override void dealloc() {
        NSLog($"dealloc obj {mTag}");
    }
}

[UIApplicationMain, IBObject]
class AppDelegate : IUIApplicationDelegate {

    public BOOL application(UIApplication application) didFinishLaunchingWithOptions(NSDictionary launchOptions) {
        var window = new UIWindow(UIScreen.mainScreen().bounds);
        window.rootViewController = new UIViewController withNibName(null) bundle(null);
        window.makeKeyAndVisible();

        // 1) array[0] will never be deallocated
        var array = new TestClass[] {new TestClass("#1")};
        Action a1 = () => array[0].test();
        a1 = null;

        // 2) obj will be deallocated
        var obj = new TestClass("#2");
        Action a2 = () => obj.test();
        a2 = null;

        return true;
    }
    ...

(RemObjects) #2

Thanks, logged as bugs://75545


(RemObjects) #3

bugs://75545 got closed with status fixed.