C String Functions in Swift: a malloc’y Story
The pointer you get back points into a buffer, which doesn’t exist anymore. That is why you need to be super careful when accessing C APIs.
[…]
Why does this [Objective-C] rarely result in an allocation? In the case above the
NSString
is anNSConstantString
which is already backed by an UTF-8 string, and as mentioned above, a lot ofNSString
’s are backed by UTF-8.[…]
I was incorrectly assuming that Swift would create the static
String
in a way that is backed by an UTF-8 buffer, including the terminating 0 (because that byte is negligable). And more importantly, that the compiler would directly pass over the pointer to that cString buffer. […] When using C API with Swift Strings (be it a simpleputs
or maybe libxml2), be aware that such calls are really expensive (a malloc+free per call).