[swift-users] UnsafeMutablePointer<String> vs. UnsafeMutablePointer<Int>

Dmitri Gribenko gribozavr at gmail.com
Sat May 21 04:03:39 CDT 2016

Hi Adrian,

On Sat, May 21, 2016 at 1:48 AM, 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.initialize("test")
> pString.predecessor().memory // will crash ax expected
> pString.predecessor() == pString.advancedBy(-1) // true
> pString.destroy()
> pString.dealloc(1)
> where
> let iInt = UnsafeMutablePointer<String>.alloc(1)
> iInt.initialize("test")
> 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?

Yes, you did.

In the String case the crash is not guaranteed (it is a segmentation
fault, not a controlled trap).  Someone else's valid String can happen
to be located immediately before your memory chunk, and then the code
would "just work", loading that other string.

Dereferencing (reading or writing into) an out-of-bounds pointer is
undefined behavior in Swift.


(j){printf("%d\n",i);}}} /*Dmitri Gribenko <gribozavr at gmail.com>*/

More information about the swift-users mailing list