Yuval Adam
Yuval Adam

Reputation: 165340

Properly initialize a vector before passing to unsafe code

Given a piece of unsafe code (bindings to a system library) of type:

pub fn unsafe_system_call(buf: *mut ::std::os::raw::c_short) {}

I am wrapping it with a function:

pub fn wrapper(buf: &mut [u8]) {
    unsafe {
        ffi::unsafe_system_call(buf.as_ptr() as *mut _);
    }
}

Calling wrapper() with a static array buffer is possible:

let mut buf: [u8; 7] = [0, 0, 0, 0, 0, 0, 0];
wrapper(&mut buf);

But when the size of the buffer should be dynamic, and attempting to use a Vec, it's unclear how to init the buffer:

let mut buf = Vec::with_capacity(runtime_size);
wrapper(&mut buf);

This code just creates a Vec but doesn't initialize the memory in preparation of an unsafe call, and the library call doesn't execute correctly.

What's the right way to do this?

Upvotes: 2

Views: 181

Answers (1)

orlp
orlp

Reputation: 117926

You can simply create a zero-initialized vector using the vec! macro:

let mut buf = vec![0u8; runtime_size];

You can also map a fixed range (in case you need initialization based on index i) and collect it as a more general method:

let mut buf: Vec<u8> = (0..runtime_size).map(|_i| 0u8).collect();

Upvotes: 3

Related Questions