patrick
patrick

Reputation: 367

Avoiding memory leaks in jni code

I'm writing a jni code in which i have to frequently convert std::string to jstring and vice versa, for which i'm using following functions

//std::string to jstring

const char *cons_ref = ANY_STD_STRING.c_str();

jstring jref = env->NewStringUTF(cons_ref);

//jstring to std::string

const char *cons_ref = env->GetStringUTFChars(ANY_JSTRING, 0);

std::string ANY_STD_STRING = cons_ref

But this is leading to creation of a lot of const char* which are read only and cannot be deleted, thus causing memory leaks.

Is there a better technique to do these conversions to avoid memory leaks. Thanks in advance.

Upvotes: 0

Views: 2425

Answers (1)

TheUndeadFish
TheUndeadFish

Reputation: 8171

Whenever you're dealing with something that returns a pointer, you should look at the documentation for that function. Ideally it should tell you whether or not you're responsible for deallocating/releasing that memory. And if so it should tell you how.

I don't know JNI, but with a little googling I found http://docs.oracle.com/javase/7/docs/technotes/guides/jni/spec/functions.html

On that page it says:

const char * GetStringUTFChars(JNIEnv *env, jstring string, jboolean *isCopy);

Returns a pointer to an array of bytes representing the string in modified UTF-8 encoding. This array is valid until it is released by ReleaseStringUTFChars().

So it sounds like you should be doing something like:

//jstring to std::string

const char *cons_ref = env->GetStringUTFChars(ANY_JSTRING, 0);

std::string ANY_STD_STRING = cons_ref;

env->ReleaseStringUTFChars(ANY_JSTRING, cons_ref);

Upvotes: 2

Related Questions