views:

117

answers:

1

I have the following code in a c++ "listener class" (more or less), which calls some function of a Java object. I suspect there's a memory leak:

JNIEnv *env = NULL;
vm_->AttachCurrentThread(&env, NULL);
const jclass cls = env->FindClass(...);
const jmethodID meth = env->GetMethodID(...);
const jobject obj = env->NewObject(cls, meth, ...);

[ more code ]

env->DeleteLocalRef(obj);

My question is: should I also release the local reference of cls and meth? JNI Documentation isn't very clear about it.

+1  A: 

No, there is no need to do so. There is no heap allocated for those two variables, they are only local to the current method and don't have to be free'd or something.

As a rule of thumb, you have to delete JNI objects that were created with a method that has New in it's name, e.g.

env->NewStringUTF(...)
env->NewObjectArray(...)
env->NewObject(...)

because those methods all translate to some kind of memory allocation on the heap (new, malloc)

David Sauter
Thanks. It seems the memory leak is in the native library I'm linking to, and not in my JNI code.Anyway, I've just discovered Push/PopLocalFrame() and it's much easier to use them than to free every single local reference.
G B