3

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.

3
  • In addition to @IanS.'s answer, be aware that when you call Vec::new(), it will pre-allocate some memory, and even if it probably allocates less than 100 elements, it still could allocate more and simply never reallocate. Maybe, for the sake of the experimentation, you should start with a Vec::with_capacity(1) or something like that. Commented May 17, 2022 at 17:53
  • 5
    @BlackBeans That's incorrect, Vec::new() is documented to not allocate. See the third paragraph here. Commented May 17, 2022 at 17:57
  • 1
    @IanS. ah, well, my bad. Commented May 17, 2022 at 19:37

1 Answer 1

8

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.