我用jni创建了一个新的字节数组,导致内存泄漏。
我尝试了DeleteLocalRef,DetachCurrentThread和ReleaseByteArrayElements。
int on_header_field(http_parser *parser, const char *at, size_t length)
{
int attached = 0;
int ret;
jbyteArray data;
void *tmp;
HttpConnection *connection = parser->data;
JavaHttpServer *server = connection->server->data;
JNIEnv *env;
if ((*jvm)->GetEnv(jvm, &env, JNI_VERSION_1_8) == JNI_EDETACHED) {
(*jvm)->AttachCurrentThread(jvm, &env, NULL);
attached = 1;
}
data = (*env)->NewByteArray(env, length);
tmp = (*env)->GetPrimitiveArrayCritical(env, data, 0);
memcpy(tmp, at, length);
(*env)->ReleasePrimitiveArrayCritical(env, data, tmp, 0);
ret = (*env)->CallIntMethod(env, server->object, server->onHeaderField, (jlong)connection, data);
(*env)->DeleteLocalRef(env, data);
if (attached) {
(*jvm)->DetachCurrentThread(jvm);
}
return ret;
}
此功能导致内存泄漏。但是我不知道为什么。
我期望在多次运行测试时不会增加内存。我已经在没有此代码部分的情况下对其进行了测试,并且效果很好!