3 ms·
That article gives an example of where mutable aliasing isn't always dangerous: let mut my_tuple = (1, 2); let first_elem = &my_tuple.0; // error[
by Measter 3y ago
That article gives an example of where mutable aliasing isn't always dangerous:
let mut my_tuple = (1, 2);
let first_elem = &my_tuple.0;
// error[E0506]: cannot assign to `my_tuple` because it is borrowed
my_tuple = (3, 4);
println!("{first_elem}");
In that specific example it isn't a problem because the type being changed is just an integer. But if you tweak it slightly it creates a use-after-free:
let mut my_tuple = (vec![1, 2, 3], 56);
let first_elem = my_tuple.0.as_slice();
my_tuple = (vec![4, 5, 6], 23);
println!("{first_elem:?}");
In this case `first_elem` is a `&[i32]`, and when `my_tuple` is reassigned the allocation is freed while the reference still exists.