If I return a Vec buffer and a pointer to its internal data, is the pointer valid?

I’m writing some C FFI bindings, and I came up with a situation which I’m unsure whether it works or not. In its simplest form, it would be:

unsafe fn foo() -> (*const u8, Vec<u8>) {
    let buf = vec![0, 1, 2];
    (buf.as_ptr(), buf)
}

Now using it:

fn main() {
    let (ptr, _buf) = foo();

    // pass ptr to C function...
}

In the example above, is ptr valid, since _buf lives until the end of the scope?

>Solution :

The question is whether moving the Vec invalidates the pointer into it. And the answer is, it’s not decided yet.

This is UCG issue #326.

So it is best to avoid code like that until it is decided. But for what it’s worth, as a lot of code relies on that to work, I don’t believe it will be decided to be invalid.

Leave a Reply