NumPy fixed-width integer overflow

NumPy fixed-width integer overflow

Description

NumPy integers such as int8, int16, int32 and int64 have a fixed width. Arithmetic outside the type’s range can wrap to a smaller or negative value.

Potential impact

An incorrect amount, allocation size or iteration count can affect payments or resource limits.

Remediation

Find the destination type’s bounds with np.iinfo(dtype). Calculate using Python int or a wider type that can hold the result, then check those bounds before using the value.

Examples

If the base and exponent come from external input, limit the input size and exponent before calculating. Checking the result afterward cannot bound the work or memory the calculation needs.

Before

python
result = np.power(number, pow_value, dtype=np.int64)

After

python
limit = np.iinfo(np.int64).max
base = int(number)
exponent = int(pow_value)
if base < 0 or exponent < 0:
    raise ValueError("unsupported input")

result = base ** exponent
if result > limit:
    raise ValueError("too large")

The example raises a nonnegative base to a nonnegative power using Python int and rejects a result above the np.int64 maximum.

References