swiftswift-extensionsexc-bad-instruction

Data.subdata(in:) results in EXC_BAD_INSTRUCTION


While trying to retrieve subdata of a Data object, the application crashes issuing the following error:

Thread 1: EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0)

Below you can see the code. It's a Data extension. Hope someone can explain why this crashes.

public extension Data {
    /// Removes and returns the range of data at the specified position.
    /// - Parameter range: The range to remove. `range` must be valid
    /// for the collection and should not exceed the collection's end index.
    /// - Returns: The removed data.
    mutating func remove(at range: Range<Data.Index>) -> Self {
        precondition(range.lowerBound >= 0, "Range invalid, lower bound cannot be below 0")
        precondition(range.upperBound < self.count, "Range invalid, upper bound exceeds data size")
        
        let removal = subdata(in: range) // <- Error occurs here
        removeSubrange(range)
        return removal
    }
}

EDIT - added the caller functions:

This extension is called from the following function:

func temporary(data: inout Data) -> Data {
    let _ = data.removeFirst()
    return data.remove(range: 0 ..< 3)
}

Which in turn is called like this:

var data = Data([0,1,2,3,4,5])
let subdata = temporary(data: &data)

Solution

  • The error is caused by the removeFirst function. The documentation clearly states:

    Calling this method may invalidate all saved indices of this collection. Do not rely on a previously stored index value after altering a collection with any operation that can change its length.

    It appears that is exactly what is causing my error. I have replaced removeFirst with remove(at:) and it now works.