I am working with some mixed C-Swift code that has a construction for converting a C-string in a struct to a Swift string like so:
struct MyCStruct { // from the c header file
char string[75];
}
extension MyCStruct {
var swiftString: String {
get { return String(cString: UnsafeRawPointer([self.string]).assumingMemoryBound(to: CChar.self)) }
}
}
As of Swift 5.1, I started getting a sporadic memory overlap exception, possibly triggered by memory allocation elsewhere or a thread context switch. I was able to fix it by changing the get to:
get { return withUnsafePointer(to: self.string) { ptr -> String in
return String(cString: UnsafeRawPointer(ptr).assumingMemoryBound(to: CChar.self))
} }
But, I am wondering is this just masking some deeper problem unrelated to the original construction? Or, is the original construction faulty, and just lucky it never crashed before?