cognitive-engineering-lab / rust-book

The Rust Programming Language: Experimental Edition
https://rust-book.cs.brown.edu
Other
503 stars 82 forks source link

Question: why does s lose all permissions at the end of the program? #178

Closed antoniogamizbadger closed 1 week ago

antoniogamizbadger commented 3 months ago

Hi, I'm reading this section and I have found the following code:

image
fn main() {
    let mut s = String::from("hello");
    let hello: &str = &s[0..5];
    println!("{hello}");
    s.push_str(" world"); # here s loses all permissions
}

Not sure why that happens. Maybe is because is the end of the block where s is defined? If I try:

fn main() {
    let mut s = String::from("hello");
    let hello: &str = &s[0..5];
    println!("{hello}");
    s.push_str(" world");
    s.push_str(" world"); 
}

Then it works fine, which makes sense. What also makes sense, is that it fails if I try:

fn main() {
    let mut s = String::from("hello");
    let hello: &str = &s[0..5];
    println!("{hello}");
    s.push_str(" world");
    println!("{hello}");
}

Thanks and sorry if it's a trivial question! The book is amazing so thanks for creating it!

twhentschel commented 2 months ago

I'm still learning too, but I think your observation

Maybe is because is the end of the block where s is defined?

is spot on. s is no longer used in that block so it loses all permissions. See the explanation to the first example in 4.2 References Change Permissions on Paths.

block0xhash commented 2 months ago

When you do a pushthe data can get moved to another memory space where there is enough memory to store the now bigger string.

so to prevent undefined behavior the other pointers get invalidated because they will (can) be pointing to invalid data

you can try typing your program here. you will see what's going on under the hood:

https://cognitive-engineering-lab.github.io/aquascope/

image

image image

willcrichton commented 1 week ago

Similar question to #177 and cognitive-engineering-lab/aquascope#85. Please do carefully read the example at the bottom of "References Change Permissions on Paths".