Skip to content

FP in Java's BufferOverrun analysis with String.split(String, int) with non-positive limit #1971

@friedbyalice

Description

@friedbyalice

Due to an incorrect modelling of the String.split(String, int) method, when the limit is 0 or -1, the analyzer assumes the resulting array will have a size [limit, 1]; according to JavaDoc, in this case the method will either

  • behave like the String.split(String) overload, when the limit is 0
  • in some cases return one more element than the overload, when the the string ends with a match, leading to an additional empty string not being split from the result; although I think treating 0 and -1 the same way, as if the 1 argument overload had been called, would be reasonable

For example

class Test {
  void method() {
    String s = "a,b";
    String[] split = s.split(",", -1);
    int[] _unused = new int[split.length];
  }
}

split.java:5: error: Alloc May Be Negative, Length: [-1, 1].
Reports INFERBO_ALLOC_MAY_BE_NEGATIVE on the integer array allocation.

I have a possible fix here, will open a PR after adding tests and some improvement (not sure why it would ever return [-1, 1], covering literals is not enough)

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions