【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);
相关推荐
2501_916007474 分钟前
免费iOS加固方案指南
android·macos·ios·小程序·uni-app·cocoa·iphone
毕设源码-邱学长4 小时前
【开题答辩全过程】以 基于Android的综合社交系统为例,包含答辩的问题和答案
android
雨白9 小时前
玩转 Flow 操作符(二):时间控制、聚合与组合
android·kotlin
Jerry9 小时前
Compose 基础知识章节合集
android
Jerry9 小时前
Compose 布局、主题设置和动画测试
android
Zender Han9 小时前
Flutter 状态管理详解:深入理解与使用 Bloc
android·flutter·ios
程序员江同学10 小时前
Kotlin 技术月报 | 2025 年 10 月
android·kotlin
RickyWasYoung11 小时前
【matlab】字符串数组 转 double
android·java·javascript
bluetata12 小时前
Rokid AR眼镜开发入门:构建智能演讲提词器Android应用
android·人工智能·云计算·ar·ai编程
马 孔 多 在下雨12 小时前
手机App上的轮播图是如何实现的—探究安卓轮播图
android·智能手机