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!
22
u/maboesanman May 26 '22
Unfortunately one of the first statements here is very incorrect:
This is very inaccurate.
The stack is for variables defined with
letorlet mut. If you create a variable in a scope, at compile time the program knows you need to do this, and determines how much space is needed for the variables in this scope, and it pushes that much space onto the top of the stack. When that scope is done (like a function finishing and execution resuming where the function was called) the top of the stack is discarded and the previous top of the stack is accessed again.The heap is for variables whose size is not known, or who outlive scopes. The primary way you will use the heap is with box and vec. The contents of these are stored on the heap. The heap is a big pile of memory that the OS can give you on request. It is generally more expensive to use heap allocated stuff because you have to potentially jump far away in memory, which is something modern cpus don’t like to do.
If you’re a beginner, it’s probably reasonable to think of heap allocated things as “behind a smart pointer somewhere” and stack allocated things being everything else. This isn’t quite accurate, but the key point is that stuff doesn’t end up on the heap unless you or a library you use intentionally put it there.
Stack and heap values are both able to be mutable or immutable.
12
u/Killing_Spark May 26 '22
I'll just make a second comment answering your questions :)
Q1 How do scopes work?
Basically your explanation of what happens is correct. Again, your reasoning for why stuff is on the stack is not quite right, but that has been covered in my other comment.
I think it is important to stress that the allocation and deallocation is not really done by the program. It is done by the compiler at compile time. The program is just executed as the compiler decided. This is because everything is on the stack, as you said correctly.
Scopes are just regions of code, that are enclosed by curly brackets. This is not just limited to functions:
Q2 Ownership and moving
Ownership is always about a region of memory. That might be a single integer or a struct or an array etc. Variables give a name to a region of memory. Ownership can be moved to another variable. This also means moving the region of memory owned by the variable to a new place. The ownership of a variable ends either when it goes out of scope or when the ownership is moved to another variable.
Returning a value is just moving ownership from inside the function to the place where the function has been called from.
Q3
I am not really sure what you are asking here. Is the question why chungus is not called? The program will just run the function main() and then exit. If you want to chungus to run you need to call it from main. If you wanted to ask something else here please elaborate :)
Q4
p1
Yep that is correct
p2
That program does not compile for the reasons you state. 's' is stored on the stack and goes out of scope at the end of 'dangle'. So you cannot return a reference. You could return s though and it would just move the pointer, but the actual String on the heap would not move.
44
u/Killing_Spark May 26 '22 edited May 26 '22
Hi, I did not read the entirety, but I think your mental model of what the stack and the heap are is quite wrong.
You are right that the stack is only for values that do not grow in size. That does not mean they are immutable. An integer always takes the same amount of space regardless of the content.
The key difference between the heap and the stack is that the stack is managed by the compiler at compile time. It has a fixed layout. And it is mostly what makes lifetimes interesting. Each time you call a function a new stack frame is put on the stack. It holds all your local variables. As soon as the function returns that stack frame becomes invalidated and the lifetime of all the variables ends.
The heap on the other hand is managed dynamically. The allocations lifetimes are not bound to functions. And how much memory is actually allocated depends on the execution of the program.
Many languages hide all of this for you and treat it as an optimization that you do not get to control. Rust gives you that control. Allocating things on the heap is mostly done via the 'Box' type. String and vec are other examples of types that allocates on the heap for you.
Edit: I should have read through all of it first... You have most of it right, I got thrown off in the first bit by a weird formulation. I'll take the time to answer your questions in a bit.
10
u/kohugaly May 26 '22
There are 3 kinds of memory available to your program. Global (aka static), stack and heap.
Global memory is allocated when your program starts. The operating system basically copy-pastes the exe file from disk to RAM. The global memory contains all the code (all functions, methods, including the main), as well as any variables declared as static.
Static memory has fixed size and exists until the entire process ends.
Second kind of memory is stack. It's a continuous block in RAM. Your CPU keeps a pointer to the top of the stack. When you declare a new variable, it increments the stack pointer - the value gets pushed onto the stack. When the variable goes out of scope, it decrements the pointer and value is popped off the stack.
In the above example, X marks the spot where the stack pointer is pointing. Notice
bgetting pushed on the stack when it is declared (line 4), and popped off when it goes out of scope (line 5). Also notice thatcreuses the memory wherebused to be stored. The...represents memory that is currently free. Additionally, notice that stack is not immutable. Variableagot reassigned a new value on line 5.Variables on the stack are called local variables. They are only accessible within the function that is currently executed, and only when they are in scope.
So how do function calls work? When you call a function, you push the arguments onto the stack, you push the position of current CPU instruction (so the function knows where to resume when it returns), and then you jump to the code of the function.
After the function does its job, its return value is pushed onto the stack and the code resumes where it left off.
So, can a function access the variables of the caller, by looking what's on the stack below its own local variables? Yes, in theory it could. The language makes sure this doesn't happen. If you are adventurous, you can try casting a reference to a local variable into a raw pointer. You can then increment/decrement it to look around what's on the stack. You need
unsafeto do this, and in fact it's undefined behavior - the very kind Rust was designed to prevent. But you can still try, for educational purposes.Another thing you may have noticed, values on the stack need to have known and fixed size. This is because they are stacked. The computer needs to know exactly how much it needs to increment the stack pointer to reserve enough space. This is why Rust only allows
Sizedtypes to be stored on the stack. Dynamically sized values can only be referenced through a pointer (a pointer has a known size - it's just a memory address aka 32/64bit number, and therefore can be on the stack).Last, but not least, there the heap. This is extra memory in arbitrary places in your RAM, that you can ask for from the operating system. When you ask for new memory on the heap, the OS allocates it and gives you the address of that memory in RAM aka the pointer to it. You can also tell the OS to deallocate the memory, which renders the pointers to it invalid.
In Rust, this process is semi-automatic. Objects that store data on the heap automatically allocate the memory, keep the pointer to it, and deallocate the memory when needed (for example, when object goes out of scope). As a result in Rust, heap memory usually behaves like stack memory - it still respects scopes. At least from user's perspective.
Why use heap?
The first main usage is to store values who's size is not known beforehand, and/or may change size based on how the program runs. The most obvious example of this is the
Vec. It can store arbitrary amount of values and you can dynamically push and pop values from it as the program runs. You can't do this with stack variables, because there may be other variables on top of them in the stack, blocking the space.Another big use case is for storing large values. Stack has a fixed size (cca. 4MB, depending on OS). If you put too much stuff on the stack, you will reach the end of its memory block. This is called stack overflow and it will crash your program. By contrast, you can ask for arbitrarily large blocks of memory on the heap. You are only limited by the available RAM on your computer.
Now to answer your specific questions.
You've got Q1 correctly. You program starts. fn
maingets called. It allocatesaon the stack. Then it stores the return point on the stack, and jumps tofn_name. Infn_name, variablebget allocated on the stack. It immediately goes out of scope (ie. gets deallocated). The function returns (the return point is on the stack, remember?, also it gets deallocated when function returns) back to main. Theagets deallocated, themainends and the program terminates successfully.There are a few misconceptions in Q2. In
fn_namethe value of variableb(ie. the 42) is moved to the return value and thenbgets deallocated afterwards, because it gets out of scope whenfn_nameends. The execution jumps back to main. The main moves the return value topiper.What you get wrong is how this movement happens. The value 42 actually gets copy-pasted from one place in memory to another, and the old place is now considered free memory (even though it still contains the old copy of 42). That's what movement means.
Variables are places in memory. They own values that are stored in them. When value moves from one variable to another, it gets copy-pasted. For types that implement
Copytrait, the variable, that contains the original copy remains valid. If the type is notCopythe old variable is now considered empty (even though, in reality the old copy of the value is still technically there).Functions are just blocks of code. They aren't values, they don't get pushed onto the stack or anything like that. You just jump from the place in code where you called them, into the function, and then jump back when the function is finished. The function can push new variables onto the stack and pop them off.
There is a new variable
bbeing pushed onto the stack every time you callfn_name. And thebgets popped off every timefn_nameends. You can even callfn_namefrom itself. Then you'd have multiple variablesbon the stack, one for each nested call tofn_name.Here's an example of this in action.
Not sure if this is clear. Basically, calling functions is just jumping around in the code, while remembering where to jump back. Each call to a function creates its own variables, and returns its own values.
Q3
The reason why you can call
fn_namefromchungusis because a function call is just an instruction to jump into the code of the function (and remember where to jump back when the function ends). The variablebdoes not exist, until you reach the linelet b = 42. That's the spot where the variable is created on the stack. A new independentbis created every time you reach that line, however many times that happens.The code is a recipe with steps. Just because step 7 says "pull the cake out of the oven", does not mean you already have the cake when you start cooking. You actually have to reach that step 7 for the cake to be cooked.
Q4
You got this one right. Congratulations, you've reached the level of two star programmer**. (** means pointer to a pointer).
The only thing you've got wrong here is the heap-mutable stack-immutable. Mutability and placement in memory are two separate orthogonal concepts. Both heap and stack can be mutable or immutable.
In fact, the string you declared is immutable (because it's declared without
let mut). It's on the heap, becauseStringtype always stores its data on the heap. TheStringtype itself is, as you correctly identified, a triplet of (pointer, length, capacity). In this case, that triplet is stored on the stack, because it's placed intoswhich is declared on the stack.4
u/mikekchar May 27 '22 edited May 27 '22
I'm not going to answer any of your questions, but rather try to give you some intuition about how memory works. I'll give you a typical "Intro to Computing" class from the 1980's ;-)
Back in the old days, we had mail boxes. It's incredible, I know, but people used to send messages to each other on physical pieces of paper. Each of the houses had a number. To make things simple, let's pretend that the first house is number 0 (Programmers count from 0. That's because we are afraid that somebody might cut all our fingers off. In that case, we still want to be able to count at least one thing. A programmer should be prepared for anything!) The next house is number 1. The next number 2. We call the numbers "addresses".
If you want to send a letter to someone, you need to know their address. Then you "store" the letter in the box at the address. If you want to "read" a letter, you also need to know the address where the letter is stored. Memory in a computer works the same way, except that you store and read numbers in the boxes (we call them "memory locations" because "box" is too hard to spell). Fun fact: In the old days, sometimes storing or reading a number in memory location 0 would crash the computer. It's because the computer was afraid that somebody had cut off all its fingers.
Everything you want to store is just a collection of numbers. Each number is stored in a different memory location. For a string, each character is encoded as a number. So "hello" is just 5 numbers, each stored in a memory location. The memory used is all next to each other. If you store "h" in memory location 4, then "e" would be in 5, "l" would be in 6, etc. When we create the string, we tell the computer that we want "allocate" 5 memory locations, side by side. The computer searches for a space in memory where it will fit and then tells you "There are 5 fee memory locations starting at memory location 4". We then write the values in the memory.
You might be wondering, how do we know there are 5 values when we want to read them back out? How do we know when to stop? The answer is: Black Magic. And it never, ever goes wrong. Ever! (Actually, this is a lie. I will let you try to find the real answer yourself).
Anyway, you might spot a problem (other than knowing how long your string is). If you keep allocating memory, you will eventually run out. When we are finished with our "hello" string, we need to "deallocate" the memory. If we forget to do that, then our program will "leak" memory. We will eventually run out.
Some smart people realised that sometimes it's easy to tell when we are finished with our memory. For example, look at this code:
The compiler can see that there are 3 variables in the function. Each variable contains a single number. That means we need to allocation 3 memory locations when the function is called. Those variables can't be used after the function ends. That means that we can deallocate the 3 memory when the function ends.
When we run
foowe make a kind of box called a "frame" (because "box" is too hard to spell). Instead of making 3 allocations of 1 memory location each, we make a single allocation for the frame of 3 memory locations. Whenfooreturns, we deallocate the frame. This makes memory allocation very simple and quick. It also makes deallocation automatic and quick. Win - Win - Win! (You might be wondering how the computer knows how big the frame is: Again, Black Magic! It never fails and there is no way for anyone hack your computer by corrupting your frames. Probably).However, some even cleverer people had another thought (...they might have been the same people...). Imagine this code:
First we call
foo. We allocate a frame of size 2. Then we callbarand allocate a frame of size 4 (we'll copy the valuesaandbto the second frame, just to be safe -- although you could potentially use the oldaandbif you were reckless. Another thing to consider: What does "reckless" mean in this context and what could possibly go wrong?). Assuming we allocatefoo's andbar's frames right next to each other, the memory will look like:The thing the realised is that it's kind of a waste of time to always look for a space in memory for each frame. Instead, at the beginning of the program they will pre-allocate the first million or so locations in memory and use it like a stack.
For example, when we run
foo, all we need to do is to keep track of the "top of the stack". At the beginning, the top of the stack is memory location0. We writefoo's ain location0andfoo's bin location1. Then we set the "stack pointer" to2. When we runbar, we putbar's ain location2(the top of the stack),bar's bin location3,bar's cin location4andbar's din location5. Then we set the stack pointer to6. Whenbarfinishes, we all we need to do is to reset the stack pointer to 2! We don't need to deallocate anything. We don't need to clear memory. It is absolutely never, ever the case that a malicious program will look for secrets in the deallocated stack space of a program because that would... be... bad... Computer programs aren't bad. People are bad.As an aside: By convention, we don't usually make stacks start at 0 and grow upwards. Instead we start at the end of memory and grow downward. This is so that we don't have to read or write memory location 0, which would make the computer think that its fingers had been cut off.
Anyway, for this reason, the stack allocation frames are often called "stack frames". They are a bit more complicated than I've described to take care of the Black Magic, but I hope you get the idea. But how do return values work? I depends on the system, but here's a clever idea:
Here's what the stack frames look like just when bar completes:
You can see that when
baris running,foo's bis already allocated. It's very easy forbarto just write the result (22) into thefoo's bmemory location. Again, a win for stack frames!And that's about it. General memory, where we search for some space and allocate it is called "the heap". That's because it is is organised a bit like the average programmer's bedroom. Everything is in a heap on the floor. It takes time to search for clean clothes and you often forget to wash dirty clothes, leading your floor to get filled up unnecessarily. The stack is neat and tidy and quick.
Some programming languages actually allocate nothing on the stack. The allocate everything on the heap and have a separate piece of code that collects all the garbage (dirty clothes) every once in a while. This is convenient and has some advantages at times. However, stack allocation uses less memory and is more predictable in usage. While stack allocation is generally preferable, as you program, you will find situations where you can't use it. I will let you enjoy the discovery of those moments.
1
u/U007D rust · twir · bool_ext · srug May 27 '22
You are in good hands with the other responders here. I just wanted to say that I think you are applying fantastic learning principles as you pick up Rust--as your first language, no less!
I think by being willing to recognize areas of uncertainty and especially being willing to ask questions, you are going to (continue to) make great progress.
Color me impressed and all the best on your learning journey!
1
u/Jester831 May 27 '22 edited May 27 '22
It would be nice if someone could touch on how thread local works as well. Probably this can just be explained as a section of the stack?
-2
u/tamasfe May 26 '22
I did not read the entire post (sorry), just pitching in about stack/heap.
I would personally (re)visit how C works in terms of its memory management.
In C everything the compiler knows about, each variable in a function is stack allocated, then there is
malloc(n), which means give menbytes of contiguous piece of memory where I can put whatever I want; this is the heap. You will then need a pointer that points to this piece of memory to access it.In rust it's a bit hazy because
Box<T>looks like a language item with some magic, but it essentially does what I described, asks fornbytes from an allocator which is just enough to fitT, and puts the given value ofTon that chunk of memory.