James Lim
James Lim

Reputation: 13054

How to check for memory leaks in JNI

In my JNI program, I use

new
delete
env->NewGlobalRef
env->DeleteGlobalRef
jvm->AttachCurrentThread
jvm->DetachCurrentThread

What is a good way to check for memory leaks rigorously?

Upvotes: 4

Views: 2430

Answers (2)

Ortwin Angermeier
Ortwin Angermeier

Reputation: 6193

  • First try to use smart pointers.
  • As Mankarse pointed out, try to use the RAII idiom whenever possible to create and delete your global references.
  • Use as less global rferences as possible
  • Free local references when constructing them in a loop

Take a look at here for managing references.

Do you already know that your native code is leaking memory?

Upvotes: 0

Mankarse
Mankarse

Reputation: 40633

Make sure that every new, env->NewGlobalRef and jvm->AttachCurrentThread is in the constructor of an object which calls the matching deallocation function in its destructor.

This is a technique called RAII, which is vital to writing any correct program in C++.

Upvotes: 3

Related Questions