Skip to content

Buffer.alloc(): A TypeError will be thrown if size is not a number. #26151

Closed
@jorangreef

Description

@jorangreef

Buffer.alloc(size) and friends (allocUnsafe(), allocUnsafeSlow()) promise that:

A TypeError will be thrown if size is not a number.

However, this contract is broken when size is NaN:

> Buffer.alloc(123+undefined)
<Buffer >

The reason is that assertSize(), which validates the size argument, does the check using typeof size !== 'number', however:

> typeof (123+undefined)
'number'

Number.isInteger() would be better:

> Number.isInteger(123+undefined)
false

Alternatively, a faster test for NaN would be swapping the range check around to throw for anything not in range (as opposed to throw for anything before 0 or after kMaxLength which is what it currently does):

if (!(size >= 0 && size <= kMaxLength)) {
  err = new ERR_INVALID_OPT_VALUE.RangeError('size', size);
}

The above snippet catches NaN.

Metadata

Metadata

Assignees

No one assigned

    Labels

    bufferIssues and PRs related to the buffer subsystem.confirmed-bugIssues with confirmed bugs.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions