Function accepting UnsafeMutablePointer is able to change value of immutable value

Originator:maxtram95
Number:rdar://22436880 Date Originated:26-Aug-2015 04:51 PM
Status:Open Resolved:
Product:Developer Tools Product Version:Xcode 7.0b6 (7A192o)
Classification:Serious Bug Reproducible:Always
 
Summary:
There is a case when function that accepts UnsafeMutablePointer can change value of immutable variable declared with let. The following code will compile and run successfully. It will show 2 and 3.

func bug(x: UnsafeMutablePointer<Int>) {
    x.memory += 1
}

func test() {
    let x: Int
    x = 1
    bug(&x)
    print(x)
    bug(&x)
    print(x)
}

Nothing must be able to change value of let, so I consider this behavior as bug.

To compare, if you'll try to assign 'x = 2' after 'x = 1' line, compilation will fail with "Immutable value 'x' may only be initialized once". But for some reason calling 'bug(&x)' is allowed to mutate immutable value.

Also, the strange thing is if I replace two lines 'let x: Int' and 'x = 1' by 'let x: Int = 1', compilation also fails with "Cannot pass immutable value as inout argument: 'x' is a 'let' constant" on lines where 'bug(&x)' is called. This is correct behavior, and the same error message should appear in the very first case.

Steps to Reproduce:
1. Install Xcode 7.0b6 (7A192o).
2. Create a playground for iOS, paste my code snippet in playground. Code compiles successfully.
3. Look at output: "2\n" and "3\n" are printed.

Expected Results:
Compilation error should occur. It should be "Cannot pass immutable value as inout argument: 'x' is a 'let' constant" on lines where 'bug(&x)' is called.

Actual Results:
Code compiles fine, immutable value is changed after its initialization.

Version:
Xcode 7.0b6 (7A192o), OS X 10.10.5.

Notes:


Configuration:
Swift 2.0, Xcode 7.0b6 (7A192o), OS X 10.10.5, building for iOS 9.0.

Attachments:

Comments


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!