How to allocate Vec data

pub struct Test{
    pub a: Vec<u8>,
    pub b: Vec<u8>,
    pub c: Vec<u8>,
    pub d: usize,
}

i want to allocate a,b,c in the heap with size d

like the function in c++ that

a = new vector(10,0);

Do you mean pre-allocating memory for the vec?

Test {
 a: Vec::with_capacity(d),
 b: Vec::with_capacity(d),
 c: Vec::with_capacity(d),
 d,
}

So you want the 3rd ctor of the std::vector right? https://en.cppreference.com/w/cpp/container/vector/vector

In this case, use vec![0; d]

Test {
    a: vec![0; d],
    b: vec![0; d],
    c: vec![0; d],
    d,
}
1 Like

i need to alloc some heap memory and page align memory
such like use

let ptr = aligned_alloc::aligned_alloc( 100 , page_size::get());
let a  = Vec::from_raw_parts( ptr as *mut u8, 100 ,100 );

the above code is work with stack memory but i need to call it in heap

Box::<[u8]>::from_raw() ....

please refer to my reply.

i want to allocate some page-align heap memory.

from_raw_parts is not safe to use with any memory that hasn't been allocated by another Vec, or at least Rust's default allocator with exactly the size and alignment that Vec expects. It may crash horribly if you use any other allocator with it.

If you want Vec's content to be page-aligned, you must put elements in it that require such alignment, e.g. Vec<PageAlignedStruct> where the struct has #[repr(align(4096))] (or some other size).

You can use https://lib.rs/c_vec to have a Vec-like container backed by memory allocated elsewhere.

2 Likes

The variable-size part of Vec is always allocated on the heap. It is managed by the fixed-size part of Vec, which is a 3-usize smart pointer allocated on the stack, or in another containing struct or enum. The current layout of the 3-usize Vec smart pointer is
  {starting_address: usize, allocated_storage_size: usize, current_vec_length: usize}.
It is the starting_address component that can have an alignment requirement (for the referenced storage).

1 Like

can you show me some code?
because i don't know how to get page-align memory

Best way to get page aligned memory would be to allocate some new pages. To do so, check the memmap crate.

2 Likes

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.