Swift 中递归调用期间的 BAD_ACCESS [英] BAD_ACCESS during recursive calls in Swift

查看:35
本文介绍了Swift 中递归调用期间的 BAD_ACCESS的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在玩 Swift 时,我遇到了崩溃的情况,但我仍然没有弄清楚原因.

While toying with Swift, I've encountered a situation which crashes and I still not have figured out why.

让我们定义:

class TestClass {

    var iteration: Int = 0

    func tick() -> Void{
        if iteration > 100000 {
            print("Done!")
            return
        }
        iteration++
        tick()
    }
}

tick() 函数调用自身并且每次增加 iteration.任何类型的调用

The tick() function calls itself and each time increments iteration. Any call of the type

let test = TestClass()
test.tick()

在相当少量的递归(在我的 iMac 上大约 50000)后使程序崩溃,并出现 EXC_BAD_ACCESS 错误:

makes the program crash after a rather small number of recursions (around 50000 on my iMac), with a EXC_BAD_ACCESS error:

如果我定义一个类似的 struct 而不是 class,则不会出现崩溃(至少不在这些限制中).请注意,当它崩溃时,程序仅使用几 MB 的 RAM.

If I define a similar struct instead of a class, there is no crash (at least not in these limits). Note that when it crashes, the program uses only a few MB of RAM.

我还无法解释为什么会崩溃.有人有解释吗?callbackStorage 值似乎很可疑,但我没有找到任何指针.

I can't explain yet why this crashes. Does anybody have an explanation? The callbackStorage value seem suspicious but I haven't found any pointer on this.

推荐答案

您在此处遇到的运行时错误是堆栈溢出.您在修改定义以使用结构体时没有遇到它的事实并不意味着它不会发生.稍微增加迭代深度,您还可以使用结构实现实现相同的运行时错误.由于隐式参数被传递,它会在类实现中更快地达到这一点.

The runtime error that you are experiencing here is a stack overflow. The fact that you do not experience it when modifying the definition to use a struct does not mean it will not occur. Increase the iteration depth just slightly and you will also be able to achieve the same runtime error with the struct implementation. It will get to this point sooner with the class implementation because of the implicit arguments being passed around.

这篇关于Swift 中递归调用期间的 BAD_ACCESS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆