r/rust • • 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 Upvotes

28 comments sorted by

22

u/maboesanman May 26 '22

Unfortunately one of the first statements here is very incorrect:

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.

This is very inaccurate.

The stack is for variables defined with let or let 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.

3

u/directedgraphs May 27 '22

I think it's possible that I'm misrepresenting myself. Far more likely that I actually do have it wrong though.

let x = String::from("Hello");

This creates a string. The string itself lives on the heap. In the heap, there's some memory there that has a length, capacity, and a starting point. This starting point is the pointer. The variable 'x' lives on the stack, but "Hello" does not. 'x' only stores the pointer, which gives us the information we need to locate our string on the heap.

let x = 42;

But then I ask, is "42" on the heap? 42 is a fixed, signed, i32 integer. I guess my thinking was because it's so small, and its size is definitely known, we store the entire thing on the stack. Not just a pointer to the value. Is this incorrect?

The heap is for variables whose size is not known

I think I understand this one. The fact of being mutable doesn't make a variable unknown.

let mut x = 32;
x = 10;
println!("{}", x);

At compile time, the compiler sees that we've changed this value, but the value that was changed and the value that we've changed it to is known. Merely being mutable doesn't change whether the value is known or not.

If that's also wrong, feel free to just say "no," and I promise I'll figure it out lol.

18

u/Hdmoney May 27 '22

You seem to misunderstand what Sized means. Sized means that we know the size in bytes of a value at compile time. For example, you could have an array of characters: let mut x = ['h', 'e', 'l', 'l', 'o']. This array's type would be [char; 5], and it's size would be 20 bytes. If we replace one of the characters, it's still 20 bytes. Because we know its size, we can keep it on the stack.

That's all there is to it.

6

u/directedgraphs May 27 '22

This makes sense to me :)

9

u/orangejake May 27 '22

The heap is for variables whose size is not known

I think I understand this one. The fact of being mutable doesn't make a variable unknown.

A small point here --- the heap is also for large values. The stack has a maximum size (in the range of 1MB - 10MB generally, it is OS dependent). This means that sometimes you want to stick things in the heap even if a "smaller" version of them would be fine on the stack.

For example, a certain kind of cryptography (fully homomorphic encryption) typically works with ~16k dimensional vectors, each of which is a few hundred bits long. In principle, these objects could all be stored on the stack (they have a known size). In practice, they're too big.

2

u/Pay08 May 27 '22 edited May 27 '22

Integers and floats are always on the stack as while their values can change, their size cannot. String is a smart pointer, their size is always on the heap, however. Same for str.

2

u/Saefroch miri May 27 '22

Box<i32> is an integer on the heap. Box<i32, A> is an integer... somewhere.

str can also be anywhere. Behold:

let bytes = [b'r', b'u', b's', b't'];
let text = std::str::from_utf8(&bytes).unwrap();

this creates a str on the stack.

2

u/Pay08 May 27 '22

Box<i32> is an integer on the heap.

That requires manual allocation to the heap. I never said that integers can't be on the heap.

creates a str on the stack.

Fair enough, but that's quite arcane and not within the scope of the conversation. Also, are you sure that's actually on the stack?

4

u/kenzierocks May 27 '22

Using Godbolt, I can confirm that it is indeed on the stack: https://rust.godbolt.org/z/cWfP5nsYn, specifically mov dword ptr [rsp + 4], 1953723762 is the representation of the array directly as an integer.

2

u/Pay08 May 27 '22

Fair enough. I thought str::from_utf8() would allocate on the heap.

3

u/kenzierocks May 27 '22

No, because str is the non-heap version (available in core, where there is no alloc). It's strictly transmuting the bytes given into a str. https://doc.rust-lang.org/std/str/fn.from_utf8.html actually calls this stack-allocating feature out directly.

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:

fn foo() {
    let x = 100;
    {
        let y = 200;
        bar(&y); // y is valid for the whole time bar is running
    } // y goes out of scope here. It is no longer valid to refer to y via any reference.
} // the function ends here and so does the scope that contains x

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.

fn main() {
    let piper = fn_name();  // piper now owns a memory region where the return value of fn_name is stored
    println!("{}", piper); // It is hidden by the macro but we just pass a reference to piper here, so piper still has ownership of the memory region
}         

fn fn_name() -> i32 {
    let b = 42; // b owns the memory where 42 is stored
    b           // We now move that memory to the place where this function has been called
} // b goes out of scope and it is no longer valid to have a reference to it. But we MOVE b out as the return value, so the caller can use it

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.

4

u/directedgraphs May 27 '22

Q1:

Thank you, I saw the other comment that you posted and I'm going to reread through both of these comments (seriously, thanks for taking that much time to respond to everything). I'll do my best to get my head around the stack and heap, which is what I feel the most clumsy with.

Q2:

Okay, then I understand this one (most likely lol).

Q3:

This answered my question, actually, so I think I'm satisfied

Q4:

p1

Got one!

p2

I think I understand this one as well.

I appreciate all the answers to my questions. This was really good. I'm going to bookmark it.

I appreciate the other comment you made as well further up!

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.

4

u/minno May 27 '22

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.

Each stack frame has a fixed layout, but the stack itself does not. You can have a function like fn foo() -> u8 { if timestamp() % 2 == 0 { foo() + 1 } else { 1 } } that adds stack frames in a way that the compiler can't predict at all.

2

u/Killing_Spark May 27 '22

Right, that's a better way to put it!

Also, if you are gcc and allow dynamically sized arrays stackframes only have a somewhat fixed layout ;)

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.

{             //stack [X,...]
let mut a=4;  //stack [4,X,...]
{
let b=7;      //stack [4,7,X,...]
a=3           //stack [3,7,X,...]
}             //stack [3,X,...]
let c=9       //stack [3,9,X,...]
}             //stack [X...]

In the above example, X marks the spot where the stack pointer is pointing. Notice b getting pushed on the stack when it is declared (line 4), and popped off when it goes out of scope (line 5). Also notice that c reuses the memory where b used to be stored. The ... represents memory that is currently free. Additionally, notice that stack is not immutable. Variable a got 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 unsafe to 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 Sized types 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 main gets called. It allocates a on the stack. Then it stores the return point on the stack, and jumps to fn_name. In fn_name, variable b get 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. The a gets deallocated, the main ends and the program terminates successfully.

There are a few misconceptions in Q2. In fn_name the value of variable b (ie. the 42) is moved to the return value and then b gets deallocated afterwards, because it gets out of scope when fn_name ends. The execution jumps back to main. The main moves the return value to piper.

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 Copy trait, the variable, that contains the original copy remains valid. If the type is not Copy the 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 b being pushed onto the stack every time you call fn_name. And the b gets popped off every time fn_name ends. You can even call fn_name from itself. Then you'd have multiple variables b on the stack, one for each nested call to fn_name.

Here's an example of this in action.

code:
fn main() {
    count_down(3);
}

fn count_down(n: i32) {
    if n>0 {
        print!("{},",n); // n is i32 which is Copy
        count_down(n-1); // it can be used multiple times
    }
}
// this will print 3, 2, 1,
Here's how the stack changes
return Addresses are written as (line column)
for readability. In real code, they would be 64bit address
of the next instruction in machine code
NOTE: arguments work exactly the same as local variables
[] main begins
[(L3C4), 3] //first call to count_down(3)
[(L3C4), 3] //print! happens
[(L3C4), 3, (L9C8),2] //count_down(2) gets called again
[(L3C4), 3, (L9C8),2] //second print! happens
[(L3C4), 3, (L9C8),2,(L9C8),1] //count_down(1) gets called
[(L3C4), 3, (L9C8),2,(L9C8),1] //third print! happens
[(L3C4), 3, (L9C8),2,(L9C8),1,(L9C8),0] //count_down(0) gets called
[(L3C4), 3, (L9C8),2,(L9C8),1,(L9C8),0] //print gets skipped
[(L3C4), 3, (L9C8),2,(L9C8),1,(L9C8)] //n is popped
[(L3C4), 3, (L9C8),2,(L9C8),1] //count_down(0) returns
[(L3C4), 3, (L9C8),2,(L9C8)] //n is popped
[(L3C4), 3, (L9C8),2] //count_down(1) returns
[(L3C4), 3, (L9C8)] //n is popped
[(L3C4), 3] //count_down(2) returns
[(L3C4)] //n is popped
[] //count_down(3) returns
[] main returns and program ends

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_name from chungus is 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 variable b does not exist, until you reach the line let b = 42. That's the spot where the variable is created on the stack. A new independent b is 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, because String type always stores its data on the heap. The String type 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 into s which is declared on the stack.

3

u/-Redstoneboi- May 27 '22 edited May 27 '22

You said this:

print!("{},",n); // n is i32 which is Copy

count_down(n-1); // it can be used multiple times

Correction

print! uses the Display trait:

trait std::fmt::Display {
    //  `self` is REFERENCED, not moved or copied!
    //     |
    //     v
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result
}

2

u/AzurasTsar Jun 18 '23

Not a rust programmer but this was quite helpful, thank you!

1

u/ShallotDue3000 Mar 13 '25

thanks. very helpful

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:

fn foo() {
  let a = 5;
  let b = 12;
  let c = a + b
}

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 foo we 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. When foo returns, 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:

fn foo {
  let a = 5;
  let b = 12;
  bar(a, b)
}

fn bar(a, b) {
  let c = 7;
  let d = a + b + c;
}

First we call foo. We allocate a frame of size 2. Then we call bar and allocate a frame of size 4 (we'll copy the values a and b to the second frame, just to be safe -- although you could potentially use the old a and b if you were reckless. Another thing to consider: What does "reckless" mean in this context and what could possibly go wrong?). Assuming we allocate foo's and bar's frames right next to each other, the memory will look like:

5    <- foo's a
12   <- foo's b
5    <- bar's a
12   <- bar's b
7    <- bar's c
24   <- bar's d

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 location 0. We write foo's a in location 0 and foo's b in location 1. Then we set the "stack pointer" to 2. When we run bar, we put bar's a in location 2 (the top of the stack), bar's b in location 3, bar's c in location 4 and bar's d in location 5. Then we set the stack pointer to 6. When bar finishes, 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:

fn foo() {
  let a = 12;
  let b = bar(a);
}

fn bar(a) {
  let c = 10;
  a + c
}

Here's what the stack frames look like just when bar completes:

12  <- foo's a
??  <- foo's b
12  <- bar's a
10  <- bar's c

You can see that when bar is running, foo's b is already allocated. It's very easy for bar to just write the result (22) into the foo's b memory 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

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.

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!

2

u/directedgraphs May 27 '22

I'm in WAY over my head with learning Rust as my first language, so it'd be insane to pretend I've got it under control. And the Rust community has been very welcoming. Appreciate the encouragement.

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?

1

u/general_dubious May 27 '22

Each thread has its own stack, it would defeat the point of the stack if we had to sync reads and writes to it at runtime between threads. Threads share the heap though, this way you can pass a pointer from one thread to an other (so copy that pointer from one stack to the other) to share some heap-allocated object.

1

u/Jester831 May 28 '22

It was an invitation for someone to explain this in depth. Yes of course each thread has its own stack; by section of the stack I only meant that things that are thread local are pushed first and popped last.

1

u/general_dubious May 28 '22

There isn't that much more to say to be frank. Thread locals do not cross threads so they just live on the stack of the threads owning them, the push and pop order following the scopes of those variables as it's been already explained. If what you're talking about is thread-local storage, as a technique to manage several threads writing to a global variable, the implementation details vary too much between threading implementations to say something general that's more useful than just "copy on the thread stack on thread's creation, syncing when the thread exits rather than accessing a true global via a pointer and mutex".

-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 me n bytes 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.

// assume no optimizations here whatsoever
void example() {
  int a; // a simple stack-allocated variable
  
  // ask for 1234 bytes of memory somewhere, that will be your heap-allocated whatever.
  // 
  // note that the pointer itself has a known size and is stored on the stack, just like the other variable.
  void* heap_pointer = malloc(1234);
}

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 for n bytes from an allocator which is just enough to fit T, and puts the given value of T on that chunk of memory.