【Android】JNI报错 non-zero capacity for nullptr pointer分析

【Android】JNI报错 non-zero capacity for nullptr pointer分析

  • 背景
    某天,运行Android App时程序报错。

    Abort message: 'JNI DETECTED ERROR IN APPLICATION: non-zero capacity for nullptr pointer: 1
    in call to NewDirectByteBuffer
    from *****

  • 出错部分,调用了 NewDirectByteBuffer(原生JNI函数),创建了一块Buffer。pData是指针类型,dataSize是地址的大小。

cpp 复制代码
byteBuffer = env->NewDirectByteBuffer(pData, dataSize);

NewDirectByteBuffer对应的实现,在art/runtime/jni/jni_internal.cc中。实现如下。

cpp 复制代码
static jobject NewDirectByteBuffer(JNIEnv* env, void* address, jlong capacity) {
if (capacity < 0) {
  JavaVmExtFromEnv(env)->JniAbortF("NewDirectByteBuffer", "negative buffer capacity: %" PRId64,
								   capacity);
  return nullptr;
}
if (address == nullptr && capacity != 0) {
  JavaVmExtFromEnv(env)->JniAbortF("NewDirectByteBuffer",
								   "non-zero capacity for nullptr pointer: %" PRId64, capacity);
  return nullptr;
}

// At the moment, the capacity of DirectByteBuffer is limited to a signed int.
if (capacity > INT_MAX) {
  JavaVmExtFromEnv(env)->JniAbortF("NewDirectByteBuffer",
								   "buffer capacity greater than maximum jint: %" PRId64,
								   capacity);
  return nullptr;
}
jlong address_arg = reinterpret_cast<jlong>(address);
jint capacity_arg = static_cast<jint>(capacity);

jobject result = env->NewObject(WellKnownClasses::java_nio_DirectByteBuffer,
								WellKnownClasses::java_nio_DirectByteBuffer_init,
								address_arg, capacity_arg);
return static_cast<JNIEnvExt*>(env)->self_->IsExceptionPending() ? nullptr : result;
}

通过分析上面代码,可以看出来。当传入的地址,不为NULL,且申请的Size大于0的时候。会报错non-zero capacity for nullptr 。

因为,既然申请一段空间,那么就不应该用非空的地址去申请。

  • 综上

对应到出问题的地方。排查pData为NULL ,或者dataSzie不为0的情况,即可解决该问题。

cpp 复制代码
byteBuffer = env->NewDirectByteBuffer(pData, dataSize);
相关推荐
墨天梦4 小时前
B17_LifecycleLiveData与Flow
android·kotlin
_祝你今天愉快6 小时前
UI核心 - 绘制流程(测量、布局、绘制)
android
冬奇Lab7 小时前
LLM 驱动的自动化测试系列(07):移动端自动化(三)——Mobile-Agent-v3 与自研 GUI-Owl 模型路线
android·人工智能·测试
leobertlan10 小时前
痛苦系列 | DSP-02 频域切片:DTFT与DFT的探索
android·后端
leobertlan11 小时前
痛苦系列 | DSP-01 从连续到离散:DSP基础与采样
android·后端
事圆则缓13 小时前
Android 视频压缩上传实战:从 content Uri、转码到断点续传
android
冉冉同学16 小时前
AI Agent 开始操作真实手机:移动端自动化的 3 个新考点
android·ai编程
帅得不敢出门17 小时前
Android Framework关闭软件低电关机功能测试PMIC低电保护
android
恋猫de小郭17 小时前
Flutter + EmbeddingGemma 2,谷歌发布完全端侧的 AI Edge Foresight
android·前端·flutter
墨天梦19 小时前
B16_Material主题与可访问交互
android·kotlin·交互