0

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?

asked Dec 15, 2014 at 14:57

1 Answer 1

4

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.

answered Dec 15, 2014 at 15:00
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.