[swift-users] UnsafeMutablePointer<String> vs. UnsafeMutablePointer<Int>
jordan_rose at apple.com
Mon May 23 11:31:35 CDT 2016
> On May 21, 2016, at 01:48, Adrian Zubarev via swift-users <swift-users at swift.org> wrote:
> I played around with UnsafeMutablePointer and realized one behavior:
> let pString = UnsafeMutablePointer<String>.alloc(1)
> pString.predecessor().memory // will crash ax expected
> pString.predecessor() == pString.advancedBy(-1) // true
> let iInt = UnsafeMutablePointer<String>.alloc(1)
> iInt.predecessor().memory // will not crash
> iInt.predecessor() == iInt.advancedBy(-1) // true
> iInt.predecessor().memory = 42 // did I just modified some memory I don't own?
> Is this intended? This is really the case where its unsafe.
Dmitri’s answers are all better for this specific discussion, but in general, “unsafe” in Swift means “if you don’t follow the rules, this may crash, may silently corrupt memory or do other bad things, may cause other code to be optimized out or miscompiled, may be harmless”. In this particular case, it’d be hard to check for the validity of the pointer while also being fast and binary-compatible with C.
-------------- next part --------------
An HTML attachment was scrubbed...
More information about the swift-users