Search code examples
javac++java-native-interface

How to check for memory leaks in JNI


In my JNI program, I use

new
delete
env->NewGlobalRef
env->DeleteGlobalRef
jvm->AttachCurrentThread
jvm->DetachCurrentThread

What is a good way to check for memory leaks rigorously?


Solution

  • Make sure that every new, env->NewGlobalRef and jvm->AttachCurrentThread is in the constructor of an object which calls the matching deallocation function in its destructor.

    This is a technique called RAII, which is vital to writing any correct program in C++.