Integer overflow gives EXC_BAD_INSTRUCTION in Swift

╄→гoц情女王★ 提交于 2019-12-19 18:39:31

问题


While messing around with Swift, I noticed that when the 64 bit integer overflows, I get the following error:

file:///Users/user/Documents/playground/MyPlayground.playground/: error: Playground execution aborted: Execution was interrupted, reason: EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0).

func fibonacci(which: Int) -> (fibOf: Int, isEqualTo: Int) {
    var i = 1, j = 1

    for var k = 2; k < which; k += 1 {
        let tmp = i + j // this line is highlighted when error occurs
        j = i
        i = tmp
    }

    return (which, i)
}

print (fibonacci(92))
print (fibonacci(93)) // this triggers an error

The first call, i.e. with 92 as argument, will run fine. When supplying the 93 value however, I get the irrelevant EXC_BAD_INSTRUCTION error. Is this a bug or what? Normally I'd expect it to overflow.


回答1:


It is expected behaviour. If you want to overflow, you need to use overflow operators.

  • Overflow addition (&+)
  • Overflow subtraction (&-)
  • Overflow multiplication (&*)


来源:https://stackoverflow.com/questions/31417588/integer-overflow-gives-exc-bad-instruction-in-swift

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!