create_input_stream: malloc 失败时泄漏 JNI 全局引用
Author: QiuYucheng2003Created Sep 21, 2026Updated Sep 21, 2026
问题
app/src/main/cpp/jni/stream/input_stream.c 的 create_input_stream 会先把 buffer 提升为 JNI 全局引用,再 malloc 分配 InputStream。malloc 失败时直接 return NULL,没有 DeleteGlobalRef。
JNI 全局引用不会在 native 返回时自动释放。destroy_input_stream 虽然会删 is / buffer,但依赖已经分配好的结构体,这条失败路径走不到,buffer 会一直留在全局引用表里。
代码
buffer = (*env)->NewByteArray(env, BUFFER_SIZE);
buffer = (*env)->NewGlobalRef(env, buffer); // 已创建全局引用
if (buffer == NULL) {
return NULL;
}
InputStream* inputStream = (InputStream*) malloc(sizeof(InputStream));
if (inputStream == NULL) {
LOGE(MSG("Out of memory"));
return NULL; // 未 DeleteGlobalRef(buffer)
}
对应清理在 destroy_input_stream:
(*env)->DeleteGlobalRef(env, (*inputStream)->is);
(*env)->DeleteGlobalRef(env, (*inputStream)->buffer);
修复建议
在 malloc 失败分支补上释放;或先分配结构体,成功后再 NewGlobalRef。
if (inputStream == NULL) {
LOGE(MSG("Out of memory"));
(*env)->DeleteGlobalRef(env, buffer);
return NULL;
}Source: xiaojieonly/Ehviewer_CN_SXJ