3

The memory allocation can fail, but I think Swift doesn't handle that cases. The code on github calls a non failable initializer

public convenience init?(length: Int) {
    let memory = malloc(length)
    self.init(bytes: memory, length: length, copy: false) { buffer, amount in
        free(buffer)
    }
}

EDIT: The code is from the native-Swift Foundation framework coming in Swift 3.

soyer
  • 316
  • 2
  • 10
  • 1
    Interesting question. You might get better answers at one of the mailing lists at https://swift.org/community/#mailing-lists. – Martin R Apr 14 '16 at 11:44
  • It looks like they just reserved it for a future possibility to fail without changing the interface afterwards. – Darko Apr 14 '16 at 12:24

1 Answers1

1

From the swift-users list:

"Swift’s policy on memory allocation failure is that fixed-size object allocation is considered to be a runtime failure if it cannot be handled. OTOH, APIs that can take a variable and arbitrarily large amount to allocate should be failable. NSData falls into the later category." -Chris

soyer
  • 316
  • 2
  • 10
  • So it's failable but it never fails? If the allocation fails what happens? – fpg1503 Apr 15 '16 at 14:13
  • It fails on mac. NSMutableData(length: 1000000000000000) returns nil – soyer Apr 15 '16 at 14:17
  • I get Chris' point but my doubt is: can it **actually** fail? Let's say `malloc` fails and memory is `.None`, you'll probably get a crash when trying to access that data (i.e bad access). – fpg1503 Apr 15 '16 at 14:23
  • Using the new Swift-Foundation? That's a bit intriguing to me considering the call is delegated to a non-failable initializer. – fpg1503 Apr 15 '16 at 14:24
  • No, not with the Swift-Foundation. With the current Xcode and swift 2.2 it returns nil and write some error message to the stdout. $R0: NSMutableData? = nil – soyer Apr 15 '16 at 14:34
  • It’s worth noting that `Data.init(capacity:Int)` is non-failable as of https://github.com/apple/swift-corelibs-foundation/pull/538. – Bastiaan M. van de Weerd Jul 13 '17 at 20:07