Skip to content

ArrayIndexOutOfBoundsException in SafeArray.toVariantArray() #42

@EJP286CRSKW

Description

@EJP286CRSKW

This method reads as follows:

JNIEXPORT jobjectArray JNICALL Java_com_jacob_com_SafeArray_toVariantArray
  (JNIEnv *env, jobject _this)
{
  SAFEARRAY *sa = extractSA(env, _this);
  if (!sa) {
    ThrowComFail(env, "safearray object corrupted", -1);
    return NULL;
  }
  long lb, ub;
  SafeArrayGetLBound(sa, 1, &lb);
  SafeArrayGetUBound(sa, 1, &ub);
  int num = ub - lb + 1;
  jclass vClass = env->FindClass("com/jacob/com/Variant");
  // create an array of Variant's
  jobjectArray varr = env->NewObjectArray(num, vClass, 0);
  // fill them in
  jmethodID variantCons =
         env->GetMethodID(vClass, "<init>", "()V");
  for(int i=lb;i<=ub;i++) {
    long ix = i;
    // construct a variant to return
    jobject newVariant = env->NewObject(vClass, variantCons);
    // get the VARIANT from the newVariant
    VARIANT *v = extractVariant(env, newVariant);
    SafeArrayGetElement(sa, &ix, (void*) v);
    // put in object array
    env->SetObjectArrayElement(varr, i, newVariant);
  }
  return varr;
}

The problem is the variable i in the SetObjectArrayElement() call. It is running from lower to upper bound of the SafeArray, which is at least 1 for the lower bound, possibly a much larger number. Basically the issue is that SafeArray is indexed from at least 1 and Java arrays are indexed from zero.

Solution:

    // put in object array
    env->SetObjectArrayElement(varr, i-lb, newVariant); // Use 'i-lb' here, not 'i', for 0-relative Java array.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions