Swift: Casting C String to UnsafePointer<GLchar> generates garbage

Originator:iosdeveloperzone
Number:rdar://26339563 Date Originated:17-May-2016 10:19 PM
Status:Behaves Correctly Resolved:25-May-2016 11:44 AM
Product:iOS SDK Product Version:iOS 9.3 SDK
Classification:Serious Bug Reproducible:Always
 
Summary:

Given a Swift string:
    let code = "uniform mat4 u_mvpMatrix; attribute vec4 a_position; attribute vec4 a_color; varying vec4 v_color; void main() { v_color = a_color; gl_Position = u_mvpMatrix * a_position; }"

This code:
	let utf8String = UnsafePointer<GLchar>(code.cStringUsingEncoding(NSUTF8StringEncoding)!)
Produces random results in utf8String

This code:
        let utf8String = code.cStringUsingEncoding(NSUTF8StringEncoding)!
        let unsafeString = UnsafePointer<GLchar>(utf8String)
Produces the expected result.

Steps to Reproduce:
Run the tests in the attach project.

Note the test `testFailsRandomly`, which contains the first example above,  fails about 99% of the time while the test `testNeverFails` never fails. The `testFailsRandomly` generally succeeds once after restarting Xcode.

Expected Results:
Both tests should succeed. The combined expression should yield the same results as the two-step expression.

Actual Results:
The single line expression generates garbage.

Comments

The problem here, which I failed to see, is the scope of the temporary value generated by code.cStringUsingEncoding(NSUTF8StringEncoding)! in the UnsafePointer(...) initializer. As soon as the initializer has been executed, the temporary goes out of scope and is released and utf8String is left pointer to invalid memory; it is an UnsafePointer after all!

In the two line case the pointer unsafeString does not become invalid until utf8String goes out of scope.

By iosdeveloperzone at May 25, 2016, 6:51 p.m. (reply...)

Please note: Reports posted here will not necessarily be seen by Apple. All problems should be submitted at bugreport.apple.com before they are posted here. Please only post information for Radars that you have filed yourself, and please do not include Apple confidential information in your posts. Thank you!