Skip to content

Instantly share code, notes, and snippets.

@EDDxample
Created June 24, 2023 02:53
Show Gist options
  • Save EDDxample/ef6ca0a2a8c7e09016b4907aec440f80 to your computer and use it in GitHub Desktop.
Save EDDxample/ef6ca0a2a8c7e09016b4907aec440f80 to your computer and use it in GitHub Desktop.
Analysis of the Stack/Heap layout of a simple Vec<String> object.
use std::mem;
fn print_mem_bytes(ptr: *const u8, limit: usize) {
for i in 0..limit as isize {
print!("{:02x} ", unsafe { *ptr.offset(i) });
}
println!();
}
fn main() {
// Stack:
// - Vector { capacity, ptr_to_first_element, length }
// Heap:
// - String { capacity, ptr_to_str, length }
// - str {"hello"}
let mut arr: Vec<String> = Vec::with_capacity(0xEE);
arr.push("hello".to_owned());
let arr_ptr: *const u8 = &arr as *const _ as *const u8;
let string0_ptr: *const u8 = &arr[0] as *const _ as *const u8;
let str0_ptr: *const u8 = arr[0].as_str() as *const _ as *const u8;
print!("\nVector data at ${arr_ptr:018p} (Stack):\n\n\t");
print_mem_bytes(arr_ptr, mem::size_of_val(&arr));
print!("\nVector[0] data at ${string0_ptr:018p} (Heap):\n\n\t");
print_mem_bytes(string0_ptr, mem::size_of_val(&arr[0]));
print!("\nVector[0]'s &str data at ${str0_ptr:018p} (Heap):\n\n\t");
print_mem_bytes(str0_ptr, mem::size_of_val(arr[0].as_str()));
// Output:
//
// Vector data at $0x0000009435fff170 (Stack):
//
// _______________________________________________________________________
// | arr.capacity | pointer to arr[0] | arr.length |
// ee 00 00 00 00 00 00 00 a0 7e 43 dd 3a 02 00 00 01 00 00 00 00 00 00 00
//
//
// Vector[0] data at $0x0000023add437ea0 (Heap):
//
// _______________________________________________________________________
// | arr[0].capacity | ptr to arr[0]'s str | arr[0].length |
// 05 00 00 00 00 00 00 00 20 4e 42 dd 3a 02 00 00 05 00 00 00 00 00 00 00
//
//
// Vector[0]'s &str data at $0x0000023add424e20 (Heap):
//
// ______________
// |h e l l o |
// 68 65 6c 6c 6f
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment