dsimms
dsimms

Reputation: 264

Do I need to clean up the char* passed to NewStringUTF?

I think yes, but the top 12 examples I found all do something not illustrative like

JNIEXPORT jstring JCALL Java_com_foo_dumbImpl(JNIEnv* env, jobject thisObj)
{
  return (*env)->NewStringUTF(env, "constant string"); 
}

so for posterity I will ask: this is bad, yes?

JNIEXPORT jstring JCALL Java_com_foo_dumbImpl(JNIEnv* env, jobject thisObj)
{
  char *leak = malloc(1024);
  leak[0] = '\0';
  return (*env)->NewStringUTF(env, leak); 
}

...and should be:

JNIEXPORT jstring JCALL Java_com_foo_dumbImpl(JNIEnv* env, jobject thisObj)
{
  char *emptystring = NULL;
  jstring r = NULL;
  emptystring = malloc(1024);
  emptystring[0] = '\0';
  r = (*env)->NewStringUTF(env, emptystring); 
  free(emptystring);
  emptystring = NULL;
  return  r;
}

Upvotes: 12

Views: 6928

Answers (2)

rmcghee
rmcghee

Reputation: 429

It's good to be concerned about memory leaks, however, in this case, there is no leak (original example). "constant string" is a literal string; it is not allocated from the heap.

So, no, you do not need to clean up the char * passed (original example).

Your edited examples are better for illustrating your point. In the edited example, yes, you need to clean up the passed string.

Upvotes: 3

dsimms
dsimms

Reputation: 264

Yes. (Just so this doesn't look unanswered.)

Upvotes: 10

Related Questions