Skip to content

🐛 Bug Report Runtime APIs node:buffer: Buffer.alloc and Buffer.allocUnsafe throw ERR_OUT_OF_RANGE for size === kMaxLength (off-by-one) #6922

Description

@Sertug17

Description

Buffer.alloc(size) and Buffer.allocUnsafe(size) incorrectly throw ERR_OUT_OF_RANGE when size === buffer.kMaxLength (2147483647), because the check uses >= instead of >. The internal createBuffer function correctly uses >, so there is an inconsistency within the same file.

Reproduction

js
import { kMaxLength } from 'node:buffer';

console.log(kMaxLength); // 2147483647

// These should succeed (kMaxLength is the maximum valid size):
Buffer.alloc(kMaxLength); // throws ERR_OUT_OF_RANGE in workerd
Buffer.allocUnsafe(kMaxLength); // throws ERR_OUT_OF_RANGE in workerd

// This correctly throws (size exceeds maximum):
Buffer.alloc(kMaxLength + 1); // throws — correct

Expected behavior (Node.js v22)

Buffer.alloc(kMaxLength) and Buffer.allocUnsafe(kMaxLength) succeed (memory permitting). Only size > kMaxLength should throw ERR_OUT_OF_RANGE.

Actual behavior (workerd)

Both throw:

RangeError [ERR_OUT_OF_RANGE]: The value of "size" is out of range.
It must be >= 0 and <= 2147483647. Received 2147483647

Note that the error message itself says "0 to 2147483647" is valid, confirming that 2147483647 should not throw.

Root cause

In src/node/internal/internal_buffer.ts, the alloc() function uses >=:

ts
// BUG — uses >= so kMaxLength throws
if (size >= kMaxLength) {
throw new ERR_OUT_OF_RANGE('size', 0 to ${kMaxLength}, size);
}

But createBuffer() in the same file correctly uses >:

ts
// CORRECT
if (length > kMaxLength) {
throw new ERR_OUT_OF_RANGE(...);
}

Fix: Change size >= kMaxLength to size > kMaxLength in alloc().

Impact

Any code calling Buffer.alloc(buffer.kMaxLength) incorrectly receives ERR_OUT_OF_RANGE when the size is valid.

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