The compiler will now emit a warning when attempting to pass a temporary pointer argument produced from an array, string, or inout argument to a parameter which is known to escape it. This includes the various initializers for the UnsafePointer/UnsafeBufferPointer family of types, as well as memberwise initializers. For example, the compiler will emit warnings compiling the following code:
struct S {
var ptr: UnsafePointer
}
func foo() {
var i: Int8 = 0
let ptr = UnsafePointer(&i)
// warning: initialization of 'UnsafePointer' results in a
// dangling pointer
let s1 = S(ptr: [1, 2, 3])
// warning: passing '[Int8]' to parameter, but argument 'ptr' should be a
// pointer that outlives the call to 'init(ptr:)'
let s2 = S(ptr: "hello")
// warning: passing 'String' to parameter, but argument 'ptr' should be a
// pointer that outlives the call to 'init(ptr:)'
}
All 3 of the above examples are unsound because each argument produces a temporary pointer only valid for the duration of the call to which they are passed. Therefore the returned value in each case references a dangling pointer. (SR-2790) https://bugs.swift.org/browse/SR-2790 (31232450)
Fixed Warning: Initialization of 'UnsafePointer' (aka 'UnsafePointer') results in a dangling pointer
This is a new warning added to Xcode 11.4 (See release notes snippet below) See also: https://stackoverflow.com/questions/60861711/initialization-of-unsafemutablerawpointer-results-in-a-dangling-pointer
Xcode 11.4 Release Notes
The compiler will now emit a warning when attempting to pass a temporary pointer argument produced from an array, string, or inout argument to a parameter which is known to escape it. This includes the various initializers for the UnsafePointer/UnsafeBufferPointer family of types, as well as memberwise initializers. For example, the compiler will emit warnings compiling the following code: struct S { var ptr: UnsafePointer
}
func foo() { var i: Int8 = 0 let ptr = UnsafePointer(&i) // warning: initialization of 'UnsafePointer' results in a
// dangling pointer
} All 3 of the above examples are unsound because each argument produces a temporary pointer only valid for the duration of the call to which they are passed. Therefore the returned value in each case references a dangling pointer. (SR-2790) https://bugs.swift.org/browse/SR-2790 (31232450)