LoginSignup
3
2

More than 5 years have passed since last update.

intのオーバーフロー対策についてstringsパッケージから学ぶ

Posted at

Golangでのオーバーフロー

golangのintは2147483647が最大値でそれ以上になるとオーバーフローが起こります

動きとしては
* 定義時に2147483647以上の値を指定するとコンパイルが失敗する
* 四則演算を行うとオーバーフローが起こるがコンパイルは通る
https://play.golang.org/p/I4e8LFr73nZ

なので四則演算がある場合はオーバーフロー対策を行う必要があります

strings.Repeatから学ぶ

strings.Repeatの動きはこんな感じです
https://play.golang.org/p/n5ulDrRR5cV

今回は標準パッケージのstrings. Repeatの対策を見てみます

オーバーフロー対策

strings.Repeat
func Repeat(s string, count int) string {
    // Since we cannot return an error on overflow,
    // we should panic if the repeat will generate
    // an overflow.
    // See Issue golang.org/issue/16237
    if count < 0 {
        panic("strings: negative Repeat count")
    } else if count > 0 && len(s)*count/count != len(s) {
        panic("strings: Repeat count causes overflow")
    }

    b := make([]byte, len(s)*count)

https://golang.org/src/strings/strings.go?s=13170:13209#L522

大事な行は以下です

オーバーフロー対策
} else if count > 0 && len(s)*count/count != len(s) {
対策を行わないとオーバーフローが起こる箇所
b := make([]byte, len(s)*count)

オーバーフローがおきるとlen(s)*countの結果が予期せぬ値(いい言い回しが思いつかなかった)がでるためlen(s)*count/count != len(s)がtrueになってしまう

https://play.golang.org/p/JqOh0jOKvmh
このリンク見たらわかるはず

3
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
2