Skip to content

Integer overflow prevention is wrong #112

@decorator-factory

Description

@decorator-factory

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions