Why Safe C Is Sometimes Unsafe Swift
In this article, I’ll look at a class of memory safety bug that occurred multiple times while I was writing the previous article. This particular bug occurs only in Release builds and can occur even when your code has no occurrence of the word “unsafe” anywhere in it.
[…]
That is the simple answer to what’s gone wrong in the Swift version: we tried to use a pointer to the first element of a tuple to read and write to the whole tuple. Creating a pointer to the first element of a larger structure and using that as a proxy for the whole structure is common in C and C++ but it’s simply not allowed in Swift.
[…]
For the example in this article, after destructuring the tuple the Swift compiler realizes that – according to the rules of the Swift memory model – only the zeroth field of the
string1
andstring2
tuples are ever read so the initialization of the remaining fields is marked as a “dead store” and the dead fields 1-9 are omitted from the function entirely (never allocated on the stack).