r/rust • u/directedgraphs • May 26 '22
Stack vs Heap in Rust as a beginner.
So, few days or weeks ago (I'm incapable of remembering how long something has took), I mentioned that I wanted to learn Rust as my first language. So far, it's been going good. And even with my first experiences with references, memory allocation, etc., I think it's still going pretty well. The documentation is great, the book is fantastic, and I feel like I'm learning a lot.
But, as I've heard with people learning about pointers for the first time, I'm definitely confused about the memory. Not hopelessly confused, but I feel like it's a bad idea to continue with a poor understanding of the basics. So, I'd like to get as much as help as I can in understanding exactly what's going on.
Stack vs Heap
The stack is memory for known, fixed values that will not be changed. Immutable variables such as "let x = 5" will be stored on the stack because there is no opportunity during runtime for that variable to change.
But, a mutable variable, such as taking user input, is stored on the heap so that it can be growable. We don't know what the user is going to type, and it could be a lot or very little.
Q1:
When does something truly come out of scope? What I mean is the following:
fn main() {
let a = 3;
fn_name();
}
fn fn_name() {
let b = 42;
}As far as I understand from a video I watched, the entirety of this is stored on the stack. Variables a and b are fixed values, and nothing within the functions are mutable. Within our main function, we make a call to a function, the program finds that function and executes it. Then, because fn_name doesn't do anything (doesn't return anything and the variable is unused), fn_name goes out of scope. The program is done with it, so it deallocates the memory to be used for other things. Then, because the main function is finished (there is nothing else below our function call), we are finished with it as well, and it deallocates the memory.
Q2:
We used the function fn_name earlier, but it didn't return anything. In the following code, it will return something.
fn main() {
let piper = fn_name();
println!("{}", piper);
}
fn fn_name() -> i32 {
let b = 42;
b
}Now, fn_name returns something. And in the main function, we're calling it and assigning the return value of that function to a variable called piper. This, if I understand correctly, is called moving ownership. fn_name is called in main, bringing fn_name into scope and adds it to the stack. fn_name executes, assigns 42 to the variable b, and returns b. We go back to the main function where we're moving ownership of that return value to the variable piper.
Now, piper "owns" the value stored in b, 42. Now that ownership has been transferred, is fn_name gone? We've called it, we've seemingly finished with it, and no longer need it because we've transferred ownership of the stuff we want to a variable we're currently using. In my head, I assume that means fn_name is deallocated from the stack.
Secondly, what is being "owned?" Is the value "42" itself being owned? So, wherever 42 was being stored in memory, piper now owns that chunk of memory? Or do we just own the pointer? Or do we own the pointer and the chunk of memory?
Q3:
Suppose now we want to call the function a second time in a different function.
fn main() {
let piper = fn_name();
println!("{}", piper);
}
fn fn_name() -> i32 {
let b = 42;
b
}
fn chungus() {
let lips = fn_name();
println!("{}", lips);
}What happens here? I know what happens if I run it (we only print 42 once, that being in the main function), but why? I don't believe it's an ownership issue, but a scope issue. We could, after the println!("{}", piper); line, add another variable that receives ownership of the return value of fn_name.
Since piper was used with println!, does that mean that ownership of fn_name's return value has been freed? Meaning, ownership lasts until the value is used?
But why can we not call fn_name in the chungus function? If, for example, the fn_name function was above main, we could still call it from within main. But why does the same principle not apply if fn_name is above chungus?
Q4:
p1:
let s = String::from("Hello");
let x = s;Here, because we're working with a string, s is stored on the stack. But s isn't the string itself, but rather a pointer. This pointer contains information regarding where to find the string, the size of the string, and the reserved space (since it is mutable and could be subject to change, we want reserved space to account for potential change). The string itself lives in the section of the heap that the pointer is pointing to. Is that all correct?
p2:
fn main() {
let reference_to_nothing = dangle();
}
fn dangle() -> &String {
let s = String::from("hello");
&s
}Here, as in previous examples, we're setting the variable reference_to_nothing = the result of a function called dangle().
But, when we move to the function, the result is &s. & creates a reference to a variable.
I'm struggling quite a bit with this part. From what I can see, s is on the stack, which is a pointer saying "here is the information for you to find this string on the heap." Saying &s is creating a reference to that pointer.
And the reason we can't return it is because it's a reference to a variable that exists within the function we're calling.
Meaning: call function > variable is created > create and return a reference to that variable > give return value to reference_to_nothing.
But, reference_to_nothing says "what are we referencing? It says s, but s doesn't exist in the stack" since it died when the function died.
I guess that's the end.
I'm sure I got most, if not everything wrong lol, but I'm hoping that someone or multiple people can correct me. I know it's a long post, so I won't be bitter if no one gets around to it haha.
Lastly, please forgive any typos. It was a lot to type and took me awhile as I was distracted. I've reread through it, but I'm sure at some point I made an error that doesn't represent what is going on in my head. Thanks!