Integer Overflow or Wraparound
- Rule ID: go_gosec_memory_math_big_rat
- Languages: go
- Source: math_big_rat.yml
Description
When converting strings to integers using strconv.Atoi
in Go, there's a risk of integer overflow if the result is assigned to a smaller integer type such as int16
or int32
. The size of the default int
type in Go is platform-dependent—64 bits on a 64-bit system and 32 bits on a 32-bit system. Overflow can occur when the value returned from strconv.Atoi
exceeds the range of the target integer type.
Remediations
✅ Check Before Conversion
Always verify that the value returned from strconv.Atoi
is within the range of the target type before conversion.
if intValue, err := strconv.Atoi(stringValue); err == nil {
if intValue >= math.MinInt16 && intValue <= math.MaxInt16 {
int16Value := int16(intValue)
// Use int16Value safely
}
}
✅ Use Specific Type Conversion Functions
Use type-specific parsing functions such as strconv.ParseInt
with the appropriate bit size to directly obtain the desired type.
if int64Value, err := strconv.ParseInt(stringValue, 10, 16); err == nil {
int16Value := int16(int64Value)
// Use int16Value safely
}
❌ Avoid Blind Type Casting
Do not cast the result of strconv.Atoi
to a smaller integer type without validating that the value fits within the smaller type's range.
❌ Don't Ignore Errors
Never ignore the error returned by strconv.Atoi
. Always handle it to catch conversion issues, including potential overflows.
Resources
Associated CWE
Configuration
To skip this rule during a scan, use the following flag
bearer scan /path/to/your-project/ --skip-rule=go_gosec_memory_math_big_rat
To run only this rule during a scan, use the following flag
bearer scan /path/to/your-project/ --only-rule=go_gosec_memory_math_big_rat
Ready to take the next step? Learn more about Bearer Cloud.