Last active
August 29, 2015 14:12
-
-
Save airspeedswift/fac00598ddeea2ff0ccc to your computer and use it in GitHub Desktop.
Runtime error when using moveInitializeFrom
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
let count = 12 | |
// Simple class that prints when it is created and destroyed | |
class Whiner { | |
let _i: Int | |
init(_ i: Int) { _i = i; println("Init: \(_i)") } | |
deinit { println("Deinit: \(_i)") } | |
} | |
var ump: UnsafeMutablePointer<Whiner> = nil | |
for i in 0..<count { | |
// allocate some fresh memory, one bigger than last time | |
var newalloc = UnsafeMutablePointer<Whiner>.alloc(i+1) | |
// initialize it from the old memory, destroying old values | |
// I thought this would de-initialize the memory pointed to | |
// by ump, and move the objects to the new memory of newallow | |
// newalloc.moveInitializeFrom(ump, count: i) | |
// after about 7 iterations (presumably the point at which alloc'd-then-freed | |
// memory is reallocated) i get the following runtime error: | |
// | |
// fatal error: UnsafeMutablePointer.moveInitializeFrom non-following | |
// overlapping range; use moveInitializeBackwardFrom | |
// I would understand this if memory is being re-used in-place, | |
// but this is instead freshly allocated memory so why would it matter? | |
// calling moveInitializeBackwardFrom eliminates the problem, | |
// but should this be necessary? | |
newalloc.moveInitializeBackwardFrom(ump, count: i) | |
// then add one more element on the end | |
newalloc.advancedBy(i).initialize(Whiner(i)) | |
// deallocate the old memory | |
ump.dealloc(i) | |
// repoint to new memory | |
ump = newalloc | |
} | |
// just to check the objects are all there correctly | |
let ubp = UnsafeBufferPointer(start: ump, count: count) | |
println(",".join(map(ubp, { toString($0._i) } ))) | |
ump.destroy(count) | |
ump.dealloc(count) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment