I have written a Hello, world program with JNI. Java calls c program with a string, c program prints that string. Here is the java program
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
public class JNISample {
public native void leakMem(String str);
static {
System.loadLibrary("sample");
}
public static void main(String args[]) throws IOException {
JNISample sample = new JNISample();
sample.leakMem("Hello world!");
}
}
Corresponding c program
#include <stdlib.h>
#include <jni.h>
#include "JNISample.h"
JNIEXPORT void JNICALL Java_JNISample_leakMem(JNIEnv *env, jobject jobj, jstring givenStr) {
const char *javaStr = env->GetStringUTFChars (givenStr, 0);
printf("Received String: %s\n", javaStr);
env->ReleaseStringUTFChars (givenStr, javaStr);
}
When I executed this program with valgrind, with following command
valgrind --trace-children=yes --show-reachable=yes --leak-check=full java -Djava.library.path=. JNISample 10 2> log
I have observed definitely lost bytes in the log, here is the valgrind’s memory summery
LEAK SUMMARY:
==5385== definitely lost: 5,246 bytes in 36 blocks
==5385== indirectly lost: 5,072 bytes in 23 blocks
==5385== possibly lost: 154,317 bytes in 131 blocks
==5385== still reachable: 6,164,933 bytes in 831 blocks
==5385== suppressed: 0 bytes in 0 blocks
Why there are definitely lost bytes with such a small program without any memory allocations? Is there any problem with JNI usage or JNI leaks memory? I have used JDK6 on Ubuntu 11.10 64 bit machine.
I cannot answer your question specifically. However, my experience with JNI is that it does a lot of things internally that can confuse valgrind. If the point at which the memory is being lost is inside JNI there wouldn’t be a lot you could do about it, anyway. However, it’s still a pain in the proverbial, since the number of different suppression needed to give you a clean run is likely to be enormous (hundreds).
Good luck.