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

Austin Zheng austinzheng at gmail.com
Thu May 26 13:36:28 CDT 2016


This is where it gets tricky.

When you create a chunk of memory using 'UnsafeMutablePointer.memory()' or
'alloc()', it's as if you are programming in C with 'malloc' and 'free'.
The memory you create and the objects you put in that memory don't
participate in ARC - the runtime will not track reference counts or
automatically free the memory. The memory will live on forever unless you
explicitly call 'dealloc()' later.

Using these APIs correctly is quite hard. If you're not careful you can
leak memory (if you lose all pointers before you've had a chance to call
dealloc), or access invalid memory (you called dealloc earlier, but
somewhere else you later access that memory). In a lot of cases a good
thing to do is to wrap your unsafe memory buffer inside a regular Swift
class, only allow the buffer to be accessed or modified through that class,
and have that class be responsible for deallocating the buffer when its
deinit is called. This way, you tie the lifetime of that buffer to your
Swift class and ARC handles the memory management for you.

Best,
Austin


On Thu, May 26, 2016 at 11:19 AM, Adrian Zubarev via swift-users <
swift-users at swift.org> wrote:

> It's also not clear sometimes exactly what "out of bounds" means - for
> example, you might have a big chunk of memory representing an array, and
> then you take a pointer to only part of that memory, representing a slice
> of the array. In this case you can write "out of bounds" of the slice, but
> the pointer type doesn't know that (because you are still within the range
> of the chunk of memory that you got from `UnsafeMutablePointer.memory()`).
>
>
> True story. :D
> Thank you for clarifying that to me, its a good example. Also the new
> pointer that I’ll get here won’t be a slice of an array just because
> `Memory` isn’t a slice. I’ll have to cast the pointer first, but I got the
> point here. ;)
>
> One more thing:
>
> - How does ARC work here when I create a new pointer to one of my
> allocated objects?
> - Do I have 2 strong references to my main piece of memory?
>
>
> --
> Adrian Zubarev
> Sent with Airmail
>
> Am 26. Mai 2016 bei 20:07:36, Austin Zheng (austinzheng at gmail.com)
> schrieb:
>
> _______________________________________________
> 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/53987ab0/attachment.html>


More information about the swift-users mailing list