NewStringUTF()和释放内存 [英] NewStringUTF() and freeing memory

查看:324
本文介绍了NewStringUTF()和释放内存的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是否应该将分配的字符串传递给 NewStringUTF()

Should I free the allocated string after passing it to NewStringUTF()?

我有一些相似的代码to:

I have some code similar to:

char* test;
jstring j_test;

test = some_function(); // <- malloc()s the memory
j_test = (*env)->NewStringUTF(env, test);

free(test); // <- should this be here?

当我将字符串传递给 NewStringUTF(),我得到一个信号11(SIGSEGV),错误addr deadbaad 错误。如果我删除 free()调用,则错误消失。我做错了什么?

When I free the string after passing it to NewStringUTF(), I get a signal 11 (SIGSEGV), fault addr deadbaad error. If I remove the free() call, the error vanishes. What am I doing wrong?

我看到了相互矛盾的意见。有人说我应该自己释放它,有人说VM会释放它,有人说VM没有释放它,你应该做一些奇怪的伏都魔术来释放它。我很困惑。

I see conflicting opinions. Some say I should free it myself, some say the VM frees it, some say the VM doesn't free it and you should do strange voodoo magic to free it. I'm confused.

推荐答案

const char * 的存储空间 NewStringUTF()的参数完全是你的责任:如果你用 malloc()分配 test ,那么你需要 free()它。所以,您发布的代码段是正确的。你正在破坏其他地方的堆。

The storage for the const char* argument to NewStringUTF() is entirely your responsibility: if you allocated test with malloc(), then you need to free() it. So, the snippet you posted is correct. You are corrupting the heap somewhere else.


我看到了相互矛盾的意见。有人说I
应该自己释放它,有人说VM
释放它,有人说VM没有释放
它你应该做奇怪的巫毒
魔法来释放它。我很困惑。

I see conflicting opinions. Some say I should free it myself, some say the VM frees it, some say the VM doesn't free it and you should do strange voodoo magic to free it. I'm confused.

他们在谈论返回的 jstring 实例 NewStringUTF()。这遵循了'本地参考文献的令人困惑的规则'

They are talking about the jstring instance returned by NewStringUTF(). That follows the confusing rules for 'local references'.

使用 DeleteLocalRef()发布此引用永远不会出错完成它。但是,如果在JVM线程的上下文中调用 NewStringUTF(),则JVM会执行一些可疑的魔法。当本机方法返回Java时,会自动清除任何泄漏的本地引用。因此,如果您确定您的最终调用者是在Java线程中,那么您可以安全地泄漏引用。

It is never an error to release this reference with DeleteLocalRef() when you are finished with it. However, the JVM performs some dubious magic if you call NewStringUTF() in the context of a JVM thread. When the native method returns to Java, any leaked local references are automatically cleaned up. So if you are sure your ultimate caller is in a Java thread, then you can safely leak the reference.

另一方面,如果您在上下文中运行一个本机线程 - 比如,一些事件报告线程向Java发出回调 - 从来没有返回到Java,所以你必须在这个<$ c $上自己调用 DeleteLocalRef() c> jstring (实际上是典型JNI调用返回的所有其他本地引用)。

On the other hand, if you are running in the context of a native thread - say, some event reporting thread making callbacks to Java - there never is a return to Java, so you must call DeleteLocalRef() yourself on this jstring (and indeed all the other local references returned by typical JNI calls).

这篇关于NewStringUTF()和释放内存的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆