[swift-dev] quick, spot the UB in this code:

Drew Crawford drew at sealedabstract.com
Wed Apr 6 23:16:44 CDT 2016

let completeFile = [112, 114, 105, 110, 116, 40, 34, 104, 101, 108, 108, 111, 32, 119, 111, 114, 108, 100, 34, 41]
let str = String(validatingUTF8: completeFile)

Did you see it?  No?

What if our bytes are not UTF8?  Well, one would hope that the constructor, um, validates them.

Turns out it does validate them, *but only if the bytes are null-terminated*.  If they are not null-terminated, we get UB <https://github.com/apple/swift/blob/510f29abf77e202780c11d5f6c7449313c819030/stdlib/public/core/CString.swift#L41>.


1.  If this constructor insists on null-terminated bytes, it should say so in the name (e.g. validatingNullTerminatedUTF8:), and it should crash deterministically if it gets non-terminated bytes, or
2.  It should not require null-terminated bytes


-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-dev/attachments/20160406/d84c387b/attachment.html>

More information about the swift-dev mailing list