Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift crashing in release build configuration but works in Debug using UnsafeBufferPointer

Tags:

swift

I am using this to remove the background of an image in swift. It works fine in Debug build configuration and crashes in the release build configuration

    func chromaKeyFilter(fromHue: CGFloat, toHue: CGFloat) -> CIFilter? {
        // 1
        let size = 64
        var cubeRGB = [Float]()

        // 2
        for z in 0 ..< size {
            let blue = CGFloat(z) / CGFloat(size-1)
            for y in 0 ..< size {
                let green = CGFloat(y) / CGFloat(size-1)
                for x in 0 ..< size {
                    let red = CGFloat(x) / CGFloat(size-1)

                    // 3
                    let hue = getHue(red: red, green: green, blue: blue)
                    let alpha: CGFloat = (hue >= fromHue && hue <= toHue) ? 0: 1

                    // 4
                    cubeRGB.append(Float(red * alpha))
                    cubeRGB.append(Float(green * alpha))
                    cubeRGB.append(Float(blue * alpha))
                    cubeRGB.append(Float(alpha))
                }
            }
        }

        let data = Data(buffer: UnsafeBufferPointer(start: &cubeRGB, count: cubeRGB.count))

        // 5
        let colorCubeFilter = CIFilter(name: "CIColorCube", parameters: ["inputCubeDimension": size, "inputCubeData": data])
        return colorCubeFilter
    }

the error is Thread 1: EXC_BAD_ACCESS (code=1, address=0x15f700020).

I do see the warning : Initialization of 'UnsafeBufferPointer<Float>' results in a dangling buffer pointer

I am guessing swift compiler optimations cause the crash but I don't how to solve this.

EDIT: I manage to avoid the crash by changing the Swift Compiler - Optimization Level to No Optimization [-Onone] but I guess it is not ideal

like image 941
Kevin Amiranoff Avatar asked Oct 17 '25 07:10

Kevin Amiranoff


1 Answers

Try

let data = withUnsafeBytes(of: value) { Data($0) }

Answer is from this question round trip Swift number types to/from Data

like image 161
Afinainflowers Avatar answered Oct 20 '25 01:10

Afinainflowers



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!