[swift-users] How to malloc in Swift 3

Joe Groff jgroff at apple.com
Fri Sep 23 16:23:21 CDT 2016

> On Sep 23, 2016, at 2:20 PM, Jens Persson <jens at bitcycle.com> wrote:
> What is the difference between:
> ptr.storeBytes(of: x, toByteOffset: offset, as: type(of: x))
> ptr.advanced(by: offset).assumingMemoryBound(to: type(of: x)).pointee = x
> ?
> I noticed that the former traps if storing to a misaligned offset while the latter is happy to do that, and I saw it mentioned as a requirement in the documentation, but other than that I'm not sure what would be the pros and cons of using the former / latter?

cc'ing Andy, who's the expert on this. AIUI, the former does not semantically bind the memory to the type being stored—informally, it has "memcpy semantics"—whereas the latter *will* bind the memory to a type, which will require all other loads and stores derived from the same pointer to remain of the same type. Neither API officially supports unaligned loads or stores yet; if one crashes and the other doesn't, that's an accident.


More information about the swift-users mailing list