【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);
相关推荐
韩仔搭建10 小时前
第二章:安卓端启动流程详解与疑难杂症调试手册
android·ui·娱乐
A-花开堪折10 小时前
Android7 Input(七)App与input系统服务建立连接
android
冰糖葫芦三剑客10 小时前
Android 自定义悬浮拖动吸附按钮
android
吃汉堡吃到饱10 小时前
【Android】从Choreographer到UI渲染(二)
android·ui
微信公众号:AI创造财富10 小时前
显示的图标跟UI界面对应不上。
android·ui
aningxiaoxixi10 小时前
安卓 Audio Stream 类型
android
奔跑吧 android11 小时前
【android bluetooth 协议分析 01】【HCI 层介绍 3】【NUMBER_OF_COMPLETED_PACKETS 事件介绍】
android·bluetooth·hci·bt·gd·aosp13
_龙小鱼_13 小时前
Kotlin扩展简化Android动画开发
android·开发语言·kotlin
奔跑吧 android14 小时前
【android bluetooth 协议分析 01】【HCI 层介绍 6】【WriteLeHostSupport命令介绍】
android·bluetooth·bt·gd·aosp13·writelehostsup·hcicmd
uwvwko14 小时前
ctfshow——web入门254~258
android·前端·web·ctf·反序列化