Skip to content

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

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.

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

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

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions