OpenCV JNI: Java/native handling of Mat - possibility for delete getting called twice?

Viewed 246

I'm working on a project where I have a Mat that is allocated on the heap in native code (at the request of some Java code), like so:

Mat* mat = new Mat(height, width, type, pointer_to_some_native_data_buffer);

I then create a Mat object in Java, and point it to that native Mat by using a pointer returned from native code:

Mat javaHandleToNativeMat = new Mat(pointerFromNativeCode);

After doing some processing on it from the Java side, I call a native method to free the Mat that was allocated at the beginning:

delete (Mat*) ptr;

My question is, could native memory corruption happen when the GC runs the finalizer method on the Java Mat that pointed to the native Mat?

The finalizer code is as follows:

    @Override
    protected void finalize() throws Throwable {
        n_delete(nativeObj);
        super.finalize();
    }

Notice that it calls n_delete(nativeObj). I'm wondering if this could be a problem, since I previously deleted the object in native code. If it is a problem, what is the best way to fix the problem? Should I simply call release() on the native Mat, and allow it to actually be deleted in the finalizer when the GC runs?

1 Answers

Since you're deleting the native Mat and the implementation of n_delete is:

JNIEXPORT void JNICALL Java_org_opencv_core_Mat_n_1delete
  (JNIEnv*, jclass, jlong self)
{
    delete (Mat*) self;
}

the GC will delete the cv::Mat pointer twice, which is BAD. You can find here a more in depth description on what deleting a pointer twice implies.

Related