The Rust Programming Language — Vectors — Stack Memory vs Heap Memory
Memory usage under the hood by variables vs vectors. Understand stack and heap memory once and for all.
As I said in the previous article, the usage of memory is different for arrays (and other variables) vs the vectors. This is fundamentally due to the nature of vectors being of an unknown size during the runtime of a program.
We’ll deep dive into usage of memory with the help of graphical examples below. To summarise something that we learnt a few articles ago here, memory is representation of series of bits in a sequence and we make sense out of it by clubbing those bits to a series of 1 byte (8 bits), 2 bytes (16 bits) and etc and generating a value out of those bits. See the image below:
Let’s take an example of below code snippet:
fn increment_decrement(num: u8) {
print_nums(num + 1, num - 1);
}
fn print_nums(x: u8, y: u8) {
println!("{} {}", x, y);
}
increment_decrement(42);
The code is fairly simple. We have a function called increment_decrement
, which as the name suggests…