'Is rust vector continuously allocated?

I am new to Rust and I am investigating vector implementation. I tried to resize vector many times and check addresses of elements with following code:

fn main() {
    let mut vector = Vec::new();

    for i in 1..100 {
        println!(
            "Capacity:{}, len: {}, addr: {:p}",
            vector.capacity(),
            vector.len(),
            &vector,
        );
        vector.push(i);
    }
    println!("{:p}", &vector[90]);
}

It gives me output (last 2 lines):

Capacity:128, len: 98, addr: 0x7ffebe7a6930
addr of 90-element: 0x5608b516bd08

My question is why 90-th element is in another memory location? I assume it should me somewhere near the 0x7ffebe7a6930 address.



Solution 1:[1]

Yes Vec stores its data in a contiguous section of memory. &vector gives you a reference to the actual Vec struct that lives on the stack which contains the capacity, pointer, and length. If instead you print vector.as_ptr() then you should get a result that makes more sense. Also, you should probably push before printing in the loop since theoretically that call to push could re-allocate on the last iteration and then your pointers would appear to be different.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Ian S.