I'm using GetStringUTFChars to retrieve a string's value from the java code using JNI and releasing the string using ReleaseStringUTFChars. When the code is running on JRE 1.4 there is no memory leak but if the same code is running with a JRE 1.5 or higher version the memory increases. This is a part of the code
msg_id=(*env)->GetStringUTFChars(env, msgid,NULL);
opcdata_set_str(opc_msg_id, OPCDATA_MSGID, msg_id);
(*env)->ReleaseStringUTFChars(env, msgid,msg_id);
I'm unable to understand the reason for leak.Can someone help?
This one is because if I comment the rest of the code but leave this part the memory leak takes place. This is a part of the code that I'm using
JNIEXPORT jobjectArray JNICALL Java_msiAPI_msiAPI_msgtoescalate( JNIEnv *env,
jobject job,
jstring msgid,
jlong msgseverity,
jstring msgprefixtext,
jint flag )
{
opcdata opc_msg_id; /* data struct to store a mesg ID */
const char *msg_id;
int ret, ret2;
jint val;
val=67;
jstring str=NULL;
jobjectArray array = NULL;
jclass sclass=NULL;
/* create an opc_data structure to store message ids of */
/* messages to escalate */
if ((ret2=opcdata_create(OPCDTYPE_MESSAGE_ID, &opc_msg_id))!= OPC_ERR_OK)
{
fprintf(stderr, "Can't create opc_data structure to store message. opcdata_create()=%d\n", ret2);
cleanup_all();
}
//////////////////////////////////////////////////////////
msg_id=(*env)->GetStringUTFChars(env,msgid,NULL);
opcdata_set_str(opc_msg_id, OPCDATA_MSGID, msg_id);
(*env)->ReleaseStringUTFChars(env, msgid, msg_id);
ret=opcmsg_ack(connection,opc_msg_id);
//////////////////////////////////////////////////////////
if(flag==0 && ret==0)
{
sclass = (*env)->FindClass(env, "java/lang/String");
array = (*env)->NewObjectArray(env, 2, sclass, NULL);
str=(*env)->NewStringUTF(env,"0");
(*env)->SetObjectArrayElement(env,array,0,str);
(*env)->DeleteLocalRef(env, str);
str=(*env)->NewStringUTF(env,"0");
(*env)->SetObjectArrayElement(env,array,1,str);
(*env)->DeleteLocalRef(env, str);
}
opcdata_free(&opc_msg_id);
if(ret!=0)
return NULL;
else
return(array);
}
In the one above is if I comment the sections between ///// I don't see any memory leak.
The only way to discover JNI memory leaks is to use a heap-dump tool that explicitly marks native references. If possible, you should not use any global references. It's better to assign the desired object to the field of a normal Java class.
What is a Memory Leak in Java? The standard definition of a memory leak is a scenario that occurs when objects are no longer being used by the application, but the Garbage Collector is unable to remove them from working memory – because they're still being referenced.
Yes. Memory leaks can still occur even when you have a GC. For example, you might hold on to resources such as database result sets which you must close manually.
Release array object.
(*env)->DeleteLocalRef(env, array);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With