[swift-users] Unsafe(Mutable)Pointer (suc)predecessor and advancedBy functions
Andrew Trick
atrick at apple.com
Thu May 26 12:14:35 CDT 2016
> On May 26, 2016, at 9:59 AM, Adrian Zubarev via swift-users <swift-users at swift.org> wrote:
>
> I’ve got one more questions about Unsafe(Mutable)Pointer. I know that I’m able to access memory that might not belong to me.
>
> My question is:
>
> Can I trust these functions that they will return a pointer to some memory when I allocate more than one object AND when I’m moving only inside that range?
>
>
Yes.
> public func successor() -> UnsafeMutablePointer<Memory>
> public func predecessor() -> UnsafeMutablePointer<Memory>
> public func advancedBy(n: Int) -> UnsafeMutablePointer<Memory>
> UnsafeMutablePointer<Int>.alloc(4) when I advance only in range of [0,1,2,3] am I safe or could I get a pointer to memory that does not belong to me?
>
>
UnsafeMutablePointer<T>.alloc(N) creates a single object in memory that holds N consecutive T values. Each value resides at index*strideof(T.self) bytes beyond the allocated pointer where index is valid in the range 0..<N.
-Andy
> Example:
>
> // imagine this is some memory portion,
> // where x is memory that does not belong to me
> // and 0 is moemory free to use
>
> […, x, 0, 0, 0 x, 0, x, …]
>
> // now I want to allocate 4 objects
> // variant A:
>
> […, x, MY1, MY2, MY3, x, MY4, x, …]
>
> // my pointer will sit at `MY1` and if I advance by 2 I'll get `x`
> // can this happen to me?
>
> // variant B:
> // Unsafe(Mutable)Pointer will ensure that I always get memory tied together
> // (or the above functions will skip memory that doesn't belong to me??):
>
>
> […, x, MY1, MY2, MY3, MY4 x, …]
> So which is right?
>
>
>
>
> --
> Adrian Zubarev
> Sent with Airmail
>
> _______________________________________________
> swift-users mailing list
> swift-users at swift.org <mailto:swift-users at swift.org>
> https://lists.swift.org/mailman/listinfo/swift-users <https://lists.swift.org/mailman/listinfo/swift-users>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-users/attachments/20160526/7ab5c730/attachment.html>
More information about the swift-users
mailing list