Dangling pointer from array

Hello, i work with pointers in my app. And compilation of something like this gives me a warning at the second line: "Initialization of 'UnsafeBufferPointer' results in a dangling buffer pointer."
And i don't get it. The lifetime of the array should be till the end of the block. Why compiler says that arrayPtr is a dangling pointer? Thank you.

do {
    var array = [0, 1, 2, 3, 4]
    let ptrToArray = UnsafeBufferPointer<Int>(start: &array, count: array.count)
    
    for number in ptrToArray {
        print(number)
    }
}

The lifetime of the array should be till the end of the block.

The lifetime lasts until the last usage (not necessarily the end of the block), although I recall there were talks about changing that in some up-coming Swift version.

The array could be dropped as early as the completion of the UnsafeBufferPointer.init(start:count:) call.

1 Like

You should use array.withUnsafeBufferPointer or a variant of it instead:

let array = [0, 1, 2, 3, 4]
array.withUnsafeBufferPointer { ptrToArray in
    for number in ptrToArray {
        print(number)
    }
}
9 Likes

It isn't just the lifetime of the Array that's the issue - &array may copy in to a temporary and only give you the address of that temporary. I believe this can happen for bridged NSArray subclasses, which may not necessarily have contiguous storage.

@dnadoba's suggestion is correct if you really, truly need a pointer. And ideally, the only reason you might need one is for C interop.

13 Likes

Thanks for such a complete answer!

Topic is closed