Skip to content

Integer overflow prevention is wrong #112

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
decorator-factory opened this issue Feb 10, 2025 · 0 comments
Open

Integer overflow prevention is wrong #112

decorator-factory opened this issue Feb 10, 2025 · 0 comments
Labels
erratum Erratum

Comments

@decorator-factory
Copy link

decorator-factory commented Feb 10, 2025

https://github.com/teivah/100-go-mistakes/blob/master/src/03-data-types/18-integer-overflows/main.go#L26-L32

func AddInt(a, b int) int {
	if a > math.MaxInt-b {
		panic("int overflow")
	}

	return a + b
}

This function panics if a is positive and b is negative.

func main() {
	AddInt(100, -20)  // panic
}

Here's an example of correctly handling overflow/underflow: https://github.com/shansec/go_code/blob/61331ebda07df6573065a1baf4fdc032884c43f6/microservices/addsrv/service.go#L40-L42

@decorator-factory decorator-factory added the erratum Erratum label Feb 10, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
erratum Erratum
Projects
None yet
Development

No branches or pull requests

1 participant