apache/flink · error · IndexOutOfBoundsException

Offset cannot be negative.

Error message

Offset cannot be negative.

What it means

Thrown by DataInputDeserializer.read(byte[], int off, int len) when off is negative. This read overload validates the destination offset before any copy, giving a clear message instead of an opaque array exception.

Source

Thrown at flink-core/src/main/java/org/apache/flink/core/memory/DataInputDeserializer.java:385

            this.position = this.end;
            return n;
        }
    }

    @Override
    public void skipBytesToRead(int numBytes) throws IOException {
        int skippedBytes = skipBytes(numBytes);

        if (skippedBytes < numBytes) {
            throw new EOFException("Could not skip " + numBytes + " bytes.");
        }
    }

    @Override
    public int read(@Nonnull byte[] b, int off, int len) throws IOException {

        if (off < 0) {
            throw new IndexOutOfBoundsException("Offset cannot be negative.");
        }

        if (len < 0) {
            throw new IndexOutOfBoundsException("Length cannot be negative.");
        }

        if (b.length - off < len) {
            throw new IndexOutOfBoundsException(
                    "Byte array does not provide enough space to store requested data" + ".");
        }

        if (this.position >= this.end) {
            return len == 0 ? 0 : -1;
        } else {
            int toRead = Math.min(this.end - this.position, len);
            System.arraycopy(this.buffer, this.position, b, off, toRead);
            this.position += toRead;

View on GitHub (pinned to 2f3c205e92)

Solutions

  1. Ensure off >= 0 before calling read(b, off, len).
  2. Use read(byte[]) when writing into the whole destination array.
  3. Validate off+len <= b.length as a combined precondition.

Example fix

// before
input.read(dst, writePos, n); // writePos may be < 0

// after
if (writePos < 0 || writePos + n > dst.length) {
    throw new IndexOutOfBoundsException("bad dst range");
}
input.read(dst, writePos, n);
Defensive patterns

Strategy: validation

Validate before calling

if (off < 0) {
    throw new IndexOutOfBoundsException("off must be >= 0, got " + off);
}
input.read(dst, off, len);

Prevention

When it happens

Trigger: Calling read(b, off, len) (or read(b) which delegates with off=0, so won't trigger) with off < 0.

Common situations: Caller computes an offset that underflows to negative; a default/uninitialized offset variable; off-by-one in a buffer-filling loop.

Related errors


AI-assisted analysis of apache/flink@2f3c205e92 (2026-08-14). Data as JSON: /api/errors/c060898b7dc71511. Report an issue: GitHub.