Skip to content

False positive RESOURCE_LEAK when closing the cursor in a method that implements an interface #246

@markusfisch

Description

@markusfisch

Closing a cursor in another method results in a false positive RESOURCE_LEAK message.

Here's a sample:

public class MainActivity extends Activity {
    @Override
    protected void onCreate(Bundle state) {
        super.onCreate(state);
        setContentView(R.layout.activity_main);

        Cursor cursor = querySomething();

        if(!closeIfEmpty(cursor)) {
            cursor.close();
        }
    }

    private Cursor querySomething() {
        return new MockCursor();
    }

    private static boolean closeIfEmpty(Cursor cursor) {
        if(cursor != null && cursor.moveToFirst()) {
            // cursor is NOT empty
            return false;
        }

        if(cursor != null) {
            cursor.close();
        }

        // cursor is empty and now closed
        return true;
    }
}

Results in:

Starting analysis (Infer version v0.6.0-ad2a906)
Computing dependencies... 100%
Analyzing 4 clusters....%
Analyzed 34 procedures in 4 files

Found 1 issue
app/src/main/java/de/markusfisch/android/inferprobeclosecursor/activity/MainActivity.java:21: error: RESOURCE_LEAK
   resource of type android.test.mock.MockCursor acquired to cursor by call to querySomething() at line 16 is not released after line 21
  19.               cursor.close();
  20.           }
  21. >     }
  22.   
  23.       private Cursor querySomething() {

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions