Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading