Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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;
}
like image 419
dsimms Avatar asked May 06 '09 00:05

dsimms


1 Answers

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

like image 182
dsimms Avatar answered Oct 21 '22 12:10

dsimms