Reputation: 7374
Consider following code:
MyClass.java:
public class MyClass {
public native void createMemoryLeak();
public static void main(String[] args) {
MyClass myObject = new MyClass();
myObject.createMemoryLeak();
}
}
MyClass.c:
#include <MyClass.h>
JNIEXPORT void JNICALL Java_MyClass_createMemoryLeak(JNIEnv *env, jobject obj)
{
char * leaked_array = malloc(sizeof(char)*100000); // This is going to be leaked
}
MyClass
has a native method createMemoryLeak()
. In this method, there is a char array allocated using malloc()
. However, this memory is not freed explicitly.
I wonder what happens to this memory when method goes out of scope. Will this code create a memory leak?
Upvotes: 0
Views: 88
Reputation: 328724
Yes, this will create a memory leak. Java doesn't care what the native code does as long as it doesn't crash.
So you need to find a way to clean up all native resources. The usual way is to wrap the native resources in some Java object and add native
methods to dispose the resources when you're done with them.
Upvotes: 4