简体   繁体   English

如何检查JNI中的内存泄漏

[英]How to check for memory leaks in JNI

In my JNI program, I use 在我的JNI程序中,我使用

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

What is a good way to check for memory leaks rigorously? 什么是严格检查内存泄漏的好方法?

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. 确保每个new env->NewGlobalRefjvm->AttachCurrentThread都在一个对象的构造函数中,该对象在其析构函数中调用匹配的释放函数。

This is a technique called RAII , which is vital to writing any correct program in C++. 这是一种称为RAII的技术,对于在C ++中编写任何正确的程序至关重要。

  • 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. 正如Mankarse指出的那样,尽可能使用RAII习语来创建和删除全局引用。
  • 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? 您是否已经知道您的本机代码正在泄漏内存?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM