【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 事件分发机制
android·java·前端
贵沫末18 分钟前
Claude Code For VS Code安装以及跳过认证
android
00后程序员张30 分钟前
完整教程:如何将iOS应用程序提交到App Store审核和上架
android·macos·ios·小程序·uni-app·cocoa·iphone
aq553560042 分钟前
ThinkPHP5.x核心特性全解析
android·数据库·oracle·php·laravel
Fᴏʀ ʏ꯭ᴏ꯭ᴜ꯭.1 小时前
MySQL高可用集群实战:MHA搭建全攻略
android·mysql·adb
00后程序员张1 小时前
iOS应用性能优化全解析:卡顿、耗电、启动与瘦身
android·ios·性能优化·小程序·uni-app·iphone·webview
程序员陆业聪1 小时前
跨端框架横评 2026:Flutter、React Native、KMP、小程序,谁是你下一个项目的正确答案?
android
aq55356001 小时前
Laravel3.x核心特性全解析
android
菜鸟国国1 小时前
Compose 点击/按压事件全解析:从基础到进阶,新手也能秒懂
android
码点2 小时前
Android 设备重启如何拿日志
android