title: JNI Freeing Memory to Avoid Memory Leak
body: <p>So i have this C++ program that is called via JNI from my Java program, the code follows:</p>
  
  <pre><code>    JNIEXPORT jstring JNICALL Java_com_entrust_adminservices_urs_examples_authn_LdapAuthenticator2_takeInfo(JNIEnv *env, jobject obj, jstring domain, jstring id, jstring idca, jstring password) 
  {
      const char *nt_domain;
      const char *nt_id;
      const char *nt_password;
      HANDLE hToken = 0;
  
      bool aut = false;
  
      nt_domain = env-&gt;GetStringUTFChars(domain, NULL);
      nt_id = env-&gt;GetStringUTFChars(id, NULL);
      nt_password = env-&gt;GetStringUTFChars(password, NULL);
  
        aut = LogonUser(nt_id, nt_domain, nt_password, LOGON32_LOGON_NETWORK, LOGON32_PROVIDER_DEFAULT, &amp;hToken );
  
        /* release buffers */
      env-&gt;ReleaseStringUTFChars(domain, nt_domain);
      env-&gt;ReleaseStringUTFChars(id, nt_id);
      env-&gt;ReleaseStringUTFChars(password, nt_password);
      /* release the login handle */
      CloseHandle(hToken);
  
      if(aut)
      {
          return env-&gt;NewStringUTF("true"); 
      }
  
      DWORD dwError = GetLastError();
        LPVOID lpMsgBuf;
  
        FormatMessage( FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, dwError, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT ), (LPTSTR) &amp;lpMsgBuf, 0, NULL );
  
      return env-&gt;NewStringUTF((const char*)lpMsgBuf); //returns the contents of lpMsgBuf (error)
  }
  </code></pre>
  
  <p>in that second to last line <code>jstring newString = env-&gt;NewStringUTF((const char*)otherString);</code> is never released, but returned, will it cause an eventual memory leak? is there anyway to get around this?</p>
  
  <p>Also is it possible that instead of returning a string i return a boolean (as returned by the LogonUser function), instead of a jstring, and instead add an "errormessage" refrence to be passed in the method, and update that? will my Java program be able to see an update to "errormessage"?</p>
  
  <p>Thanks.</p>