[swift-users] UnsafeMutablePointer<String> vs. UnsafeMutablePointer<Int>
Adrian Zubarev
adrian.zubarev at devandartist.com
Sat May 21 04:15:41 CDT 2016
So basically if I do something like this I should be on the safe side:
public class Characters {
private let reference: UnsafeMutablePointer<Character>
var characters: [Character] {
var characters = [Character]()
for index in 0..<self.count {
characters.append(self.reference.advancedBy(index).memory)
}
return characters
}
var combined: String { return String(self.characters) }
public let count: Int
public init(value: String) {
let characters = value.characters
self.count = characters.count
self.reference = UnsafeMutablePointer<Character>.alloc(self.count)
self.reference.initializeFrom(characters)
}
deinit {
self.reference.destroy(self.count)
self.reference.dealloc(self.count)
}
}
Or do I have to fix something?
Here I don’t walk out of the boundary I allocate.
Does the UnsafeMutablePointer reserves me a safe portion of memory (by safe I mean which isn’t used by anyone at the time I will start using it)?
Sure another pointer could be created and hack into my memory but that wasn’t the question. :)
Thanks.
--
Adrian Zubarev
Sent with Airmail
Am 21. Mai 2016 bei 11:04:10, Dmitri Gribenko (gribozavr at gmail.com) schrieb:
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.
Dmitri
--
main(i,j){for(i=2;;i++){for(j=2;j<i;j++){if(!(i%j)){j=0;break;}}if
(j){printf("%d\n",i);}}} /*Dmitri Gribenko <gribozavr at gmail.com>*/
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-users/attachments/20160521/5883320b/attachment.html>
More information about the swift-users
mailing list