【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);
相关推荐
传奇开心果编程1 小时前
【Jetpack Compose娓娓道来】第44课:持久化——让数据“关掉App也不丢”
android·kotlin·移动开发·数据持久化·jetpack compose·ui框架·声明式ui
星空孤辰1 小时前
【camera 008】android camera id 注册、状态监控等状态变化 全流程梳理
android·windows
恋猫de小郭3 小时前
iOS for Web ,把原生 iOS App 跑到进浏览器里面,倒反天罡
android·前端·ios
思想觉悟4 小时前
Android启动流程之点rc文件
android·linux·面试
_祝你今天愉快14 小时前
Android 高级绘制:[四] Canvas-实际案例操作
android
三少爷的鞋15 小时前
Android 工程师的技术信仰崩塌史
android
AirDroid_cn17 小时前
Android 15 权限回溯:已授予的麦克风权限如何批量回收?
android
Mr_万能胶18 小时前
官方发布,不烧心的 AOSP 编译提速技巧
android·ci/cd·架构
booboosui18 小时前
安卓 8.1 也能装了:代价是一条黄字和两个静默 bug
android
Ehtan_Zheng21 小时前
Jetpack AppState Transform:让 Compose 的响应式状态走出 UI 层
android