[swift-users] UnsafePointer<Int8> and C-String

Ole Begemann ole at oleb.net
Tue Jan 3 09:31:35 CST 2017


> What I cannot find though is the guarantee that the buffer where the
> String is converted to an UTF8 sequence is always null-terminated.
>
> I very much suspect it is, and all my tests did find a null-terminated
> string.
>
> Question: Does anybody know for sure that the buffer is always
> null-terminated? (a link to where I can check this would be most
> appreciated)

I'm not 100% certain, but I think the compiler uses this function to 
convert a String argument to a pointer:

/// Derive a UTF-8 pointer argument from a value string parameter.
public // COMPILER_INTRINSIC
func _convertConstStringToUTF8PointerArgument<
   ToPointer : _Pointer
 >(_ str: String) -> (AnyObject?, ToPointer) {
   let utf8 = Array(str.utf8CString)
   return _convertConstArrayToPointerArgument(utf8)
}

Source: Pointer.swift [1]

This in turn calls `String.utf8CString` [2], which indeed returns a 
null-terminated string.

[1]: 
https://github.com/apple/swift/blob/master/stdlib/public/core/Pointer.swift#L85-L92
[2]: 
https://github.com/apple/swift/blob/master/stdlib/public/core/StringUTF8.swift#L383-L405



More information about the swift-users mailing list