[swift-users] C Pointers and Memory

Dmitri Gribenko gribozavr at gmail.com
Fri Jul 29 03:10:04 CDT 2016


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>*/


More information about the swift-users mailing list