Swift: Repeatedly calling a closure that passes through the authentication function calls code EXC_BAD_ACCESS = 2

Update:

Here's an even simpler replay that doesn't use arrays (h / t to Tim ):

func identity<T>(_ v: T) -> T {
    return v
}

var closure = {
    return
}

while true {
    closure()
    closure = identity(closure)
}

Running this code causes a stack overflow. I am logging an error with Swift.

Original:

Original name: Swift: an array of closures calls the code EXC_BAD_ACCESS = 2

I am trying to understand why this code creates the code EXC_BAD_ACCESS = 2. Here is the code:

var closures: [() -> ()] = []
closures.append({
    return
})

while true {
    var newClosures: [() -> ()] = []
    for closure in closures {
        closure()
        newClosures.append(closure)
    }
    closures = newClosures
}

I tried to solve the problem up to a few lines, so the code may seem a little strange and meaningless. (His only “point” is to demonstrate the problem with which I have to have as few lines as possible.)

XCode macOS, , free ed. , newClosures.append(closure), . , closures to newClosures free newClosures. , , , EXC_BAD_ACCESS code = 2.

, . 17 ( 5 17 60 ). , , .

closures ,

class Foo { }

var foos: [Foo] = []
foos.append(Foo())

while true {
    var newFoos: [Foo] = []
    for foo in foos {
        newFoos.append(foo)
    }
    foos = newFoos
}

, . , - , ? , .

, , , , .

+4

Source: https://habr.com/ru/post/1694741/


All Articles