[swift-users] How to malloc in Swift 3

Andrew Trick atrick at apple.com
Fri Sep 23 16:35:14 CDT 2016

> On Sep 23, 2016, at 2:23 PM, Joe Groff <jgroff at apple.com> wrote:
>> 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.
> -Joe

storeBytes(of:as:) is an untyped memory operation. e.g. you could use it store a UInt32 to an Float’s location without binding memory.

assumingMemoryBound(to:) gives you a typed pointer, that you the programmer must guarantee is the correct type for that memory location. If you use this to get a UInt32 pointer into a Float’s location, you get undefined behavior as soon as you access the pointee.

storeBytes traps on misaligned access because memory is being reinterpreted making it easy to violate the alignment precondition.

UnsafePointer<T>.pointee never checked the alignment precondition because normally you wouldn’t need to and it’s supposed to be zero overhead.

assumingMemoryBound(to:) does not check alignment because it isn’t undefined behavior until the pointer is accessed and it’s supposed to be zero overhead.

Basically assumingMemoryBound(to:) is the one backdoor that we have for force casting pointers. The “assuming” should clue the programmer in that they really need to know what they’re doing before using it.

https://swift.org/migration-guide/se-0107-migrate.html#api-for-binding-memory-types-and-pointer-conversion <https://swift.org/migration-guide/se-0107-migrate.html#api-for-binding-memory-types-and-pointer-conversion>

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-users/attachments/20160923/4b6f39c2/attachment.html>

More information about the swift-users mailing list