Search code examples
javacmemory-leaksjava-native-interface

JNI freeing up memory


My C is quite rusty. Consider the code above: must I free up the memory for buf or each call uses the same buf array ? What is the best practice ?

JNIEXPORT jstring JNICALL Java_test_version
(JNIEnv *env, jobject obj, jint handle) {

    struct VersionNumber ver;
    versionNumber_get((void *) handle, &ver);

    char buf[30];
    snprintf(buf, 30, "%d", ver.num);

    return (*env)->NewStringUTF(env, buf);
}

Solution

  • buf is a stack variable, it will be reclaimed as the method returns, there is nothing for you to do here.

    Also because it is a stack variable it will be allocated for each method call.