【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);
相关推荐
开发之奋斗人生3 小时前
android关于pthread的使用过程
android·pthread
wu_android4 小时前
Android 视图系统入门指南
android
淡淡的香烟5 小时前
Android11 Launcher3实现去掉抽屉改为单层
android
火柴就是我5 小时前
每日见闻之THREE.PerspectiveCamera的含义
android
小书房5 小时前
Android的Dalvik和ART
android·aot·jit·art·dalvik
夏日玲子5 小时前
Monkey 测试的基本概念及常用命令(Android )
android
whysqwhw6 小时前
Transcoder代码学习-项目构建
android
夕泠爱吃糖6 小时前
Linux 文件内容的查询与统计
android·linux·c#
yzpyzp6 小时前
Kotlin的MutableList和ArrayList区别
android·kotlin
用户2018792831677 小时前
故事:《安卓公司的消息快递系统》
android