[swift-users] C Pointers and Memory

James Campbell james at supmenow.com
Fri Jul 29 03:55:19 CDT 2016


​Do you know of any resources to brush up on the pointer aspect of swift ? ​

*___________________________________*

*James⎥Head of Trolls*

*james at supmenow.com <james at supmenow.com>⎥supmenow.com <http://supmenow.com>*

*Sup*

*Runway East *

*10 Finsbury Square*

*London*

* EC2A 1AF *

On 29 July 2016 at 09:10, Dmitri Gribenko <gribozavr at gmail.com> wrote:

> On Fri, Jul 29, 2016 at 12:55 AM, James Campbell <james at supmenow.com>
> wrote:
> > So this:
> >
> > if let data = someArrayGeneratingFunction() {
> >   cFunction(UnsafeMutablePointer(data))
> > }
> >
> > Has issues with the array passed to c getting corrupted, but this
> doesn't:
> >
> > let data = someArrayGeneratingFunction()
> >
> > if let data = data {
> >   cFunction(UnsafeMutablePointer(data))
> > }
>
> Neither piece of code is guaranteed to work.  (You are just getting
> lucky that the second one happens to work.)  Array-to-pointer
> conversion only extends the lifetime of the array until the immediate
> function call returns.  So after UnsafeMutablePointer(data) returns,
> the array can be freed.
>
> Use someArrayGeneratingFunction.withUnsafeMutableBuffer { ... } instead.
>
> 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/20160729/cbed2ad2/attachment.html>


More information about the swift-users mailing list