Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Memory allocation of vector of numbers

  • extend
  • as_ptr
macro_rules! prt {
    ($var: expr) => {
        println!(
            "{:2} {:2} {:p} {:?} {:?}",
            $var.len(),
            $var.capacity(),
            &$var,
            $var.as_ptr(),
            $var
        );
    };
}

macro_rules! prtn {
    ($var: expr) => {
        println!(
            "{:2} {:2} {:p} {:?} {:?}",
            $var.len(),
            $var.capacity(),
            &$var,
            $var.as_ptr(),
            $var
        );
        for ix in 0..$var.len() {
            println!("{:2}    {:p} {:?}", ix, &$var[ix], $var[ix]);
        }
    };
}
fn main() {
    let mut numbers: Vec<i32> = vec![19, 23];

    prtn!(numbers);
    println!();
    let x = String::from("hi");
    prt!(x);

    numbers.extend([1, 2, 3, 4]);
    prtn!(numbers);
    println!();

    numbers.extend([5]);
    prtn!(numbers);
    println!();
}
 2  2 0x7ffcee29d998 0x5fc29ca5db80 [19, 23]
 0    0x5fc29ca5db80 19
 1    0x5fc29ca5db84 23

 2  2 0x7ffcee29e060 0x5fc29ca5dba0 "hi"
 6  6 0x7ffcee29d998 0x5fc29ca5db80 [19, 23, 1, 2, 3, 4]
 0    0x5fc29ca5db80 19
 1    0x5fc29ca5db84 23
 2    0x5fc29ca5db88 1
 3    0x5fc29ca5db8c 2
 4    0x5fc29ca5db90 3
 5    0x5fc29ca5db94 4

 7 12 0x7ffcee29d998 0x5fc29ca5dbc0 [19, 23, 1, 2, 3, 4, 5]
 0    0x5fc29ca5dbc0 19
 1    0x5fc29ca5dbc4 23
 2    0x5fc29ca5dbc8 1
 3    0x5fc29ca5dbcc 2
 4    0x5fc29ca5dbd0 3
 5    0x5fc29ca5dbd4 4
 6    0x5fc29ca5dbd8 5

  • The Vec contains 3 values: len, capcatity and a pointer (ptr) to where the actual vector is. This is on the stack.
  • The actual vector is on the heap.
  • In case of integers the values of the vector are in a continuous block of memory starting from the place where the ptr points to.
  • In this case we have i32 values in the vector. Each one takes up 4 bytes starting from 0x5fc29ca5db80.
  • We created another variable on the heap that was placed on 0x5fc29ca5dba0. This is 32 bytes higher.
  • As we extend the vector with 4 more numbers to have 6 elements, we can see that the vector remains in the same place. 0x5fc29ca5db80.
  • When we extend it to 7 elements taking up 7*4 = 28 bytes, we can see the vector was moved to the memory starting at 0x5fc29ca5dbc0.
  • It is unclear to me why was it already moved while we still could have added one more i32.