The following program demonstrates that a runtime crash will occur when using String
(but not eg Float
) with Array.init(unsafeUninitializedCapacity:initializingWith:)
func test<T>(value: T, count: Int) {
let a = [T](unsafeUninitializedCapacity: count) { (p, c) in
c = count
for i in p.indices { p[i] = value }
}
print(a)
}
for _ in 0 ... 5 { test(value: 123, count: 4) }
for _ in 0 ... 5 { test(value: "abc", count: 4) }
Compiling and running this:
$ swiftc --version
Apple Swift version 5.2.4 (swiftlang-1103.0.32.9 clang-1103.0.32.53)
Target: x86_64-apple-darwin19.4.0
$ swiftc test.swift && ./test
[123, 123, 123, 123]
[123, 123, 123, 123]
[123, 123, 123, 123]
[123, 123, 123, 123]
[123, 123, 123, 123]
[123, 123, 123, 123]
["abc", "abc", "abc", "abc"]
Segmentation fault: 11
Is the code doing something which will result in undefined behavior or is this crash caused by a compiler or standard library bug?
EDIT: Also (as I see now), why does it print 6 lines of [123, 123, 123, 123]
? I'd expect 5 ...
EDIT 2: never mind (thought I had written ..<
instead of ...
)