In Swift's Unsafe API, how can I allocate memory and fail with error but without crash when asking for too much?

53 Views Asked by At

In Swift's Unsafe API (on iOS), this

let p = UnsafeMutableRawPointer.allocate(byteCount: 10_000_000_000, alignment: MemoryLayout<UInt8>.alignment)

crashes, whereas C's malloc returns a nullptr when there is not sufficient memory available. So in C, one can then gracefully ask for less memory whereas with this Swift Unsafe API one just crashes. While I do not want to allocate 10 GiB (this is just for demonstration) I am still annoyed that there seems to be no mechanism to fail gracefully when allocating memory with that Swift Unsafe API and asking for too much. I feel it is not my job to know how much is too much and there should be an error message that tells me when I ask for too much. How could I do this with the Swift Unsafe API? Or should I just forget it and use C to write my manual memory allocator?

0

There are 0 best solutions below