[swift-users] Unsafe(Mutable)Pointer (suc)predecessor and advancedBy functions

Adrian Zubarev adrian.zubarev at devandartist.com
Thu May 26 12:31:02 CDT 2016


So theoretically I could build a wrapper type for Unsafe(Mutable)Pointer which will be safe to use and never exceed the allocated range!

public func successor() -> UnsafeMutablePointer<Memory>? {
     
    // return `nil` if out of range
}
So why don’t we have safe pointers today?
Any technical reasons or do I miss something here?!


-- 
Adrian Zubarev
Sent with Airmail

Am 26. Mai 2016 bei 19:14:41, Andrew Trick (atrick at apple.com) schrieb:


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
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/08b97634/attachment.html>


More information about the swift-users mailing list