This Is How Rust Stops Memory Leaks

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
c programs are prone to leaking memory and if you don't believe me let me show you a quick example read this snippet of c code here it may not be incredibly obvious but in a couple of edge cases this program will fail to free memory from the heap and ultimately leak it leaving it unable to be freed by the program leaked memory over time will waste resources available to your program and in the long run a degrade overall system performance some languages like golang for example rely on a garbage collector a garbage collector is a runtime concept that checks for segments of memory that are no longer accessible and frees them without user or programmer intervention this however comes at the cost of performance as the language needs to compile in a runtime that executes on top of the program in question this can be bulky and for lack of a better term inefficient rust on the other hand handles memory management at compile time by doing memory management at compile time rust doesn't need to rely on a runtime garbage collector to constantly be scanning for dead memory this concept is one of many that keep rust fast so how does rust do compile time memory management one way is through a concept known as ownership but to talk about ownership first we need to talk about the two types of memory allocation static and dynamic static memory allocation is used for data types that have a known size at runtime these allocations are done on the stack and at compile time the program builds an area on the stack for that value to live and its size does not change this is different however from dynamic memory allocation where a structure is allocated in the heap and can change in size as the program runs a perfect example of a dynamically allocated structure is a string that will eventually be concatenated to so to understand ownership let's take a look at this piece of rust code first we create a mutable string called s that contains the value hello because it's mutable it is allocated in the heap after we create the string we concatenate comma world exclamation point to it which expands its allocation in the heap and adds more data to it at the end of the function scope russ calls the drop function that deallocates the memory for us without us doing anything you may be saying okay that's a very straightforward concept it automatically allocates and deallocates memory who cares and that's a very good point given how simple that example was but consider this piece of code now we create a variable called s2 that is the same value as s meaning it points to the same memory where hello world lives and then we try to print the original s string this creates a problem though where at the end of our code scope how does the compiler know whether or not the memory pointed to by both s and s2 have been freed yet or not in theory it is supposed to call drop on both of these variables trying to free them but this actually creates what is known as a double free condition which is a crashing condition and as a result rust will not allow this code to compile the reason being on the line where s2 is set equal to s the value of s is thought to be wholly moved into s2 meaning that s is no longer a valid variable this creates a bit of a hassle when writing rus code though where now every time we want to use a variable that is mutable and lives in the heap we are forced to pass ownership of the variable into a function call like in this example and then return that variable back into a new variable that will be its future owner with a different appended name this feels horrible and clunky and as we write our code the list of variable names get the track on our head gets really cumbersome and hard to deal with luckily russ doesn't actually have to be like this instead of passing ownership to an ever-growing list of variables tracking the same information rust uses the idea of borrowing by using the reference symbol similar to c or c plus we tell the rust compiler that we are granting temporary ownership to a function call so that inside that function scope the variable is temporarily owned or borrowed by that function and then outside of that function scope upon return ownership is returned back to the caller see this example here we create a mutable string hello and pass it to a function called change change takes a mutable string reference as a parameter and then uses that reference to impend data to a string upon return to main s is still a valid variable now pointing to data that has been appended to despite being referenced twice s is dropped from the program as it should be given that it lives in the heap now let me be clear references aren't perfect there are some big no-nos about what you can't do when using references in rust for example one thing you're not allowed to do is return a dangling reference or a dangling pointer to an object or structure in this example here a string is created and a pointer to that string is returned this however won't compile because the string in question is created but then at the end of the function is out of scope but a reference is passed meaning that when it's returned the reference will point to a variable that no longer exists another thing you can't do in rust is reference something twice here we see a string being created and then we attempt to borrow ownership of that string twice which is not allowed borrowing a variable twice creates the opportunity for that variable either to be lost and not freed or a race condition in its access guys i hope you learned a little something in this video today about borrowing and ownership in rust and how it allows memory to be managed freely in a way that doesn't allow for memory leaks if you enjoyed this video or you learned something do me a favor hit like hit subscribe go check out my merch store link in the description and i'll see you guys in my next video take care [Music]
Info
Channel: Low Level Learning
Views: 157,945
Rating: undefined out of 5
Keywords: rust ownership, rust programming, embedded rust, rust memory safety, rust hello world, arduino, maker, craft, hobby, electronics, wires, temperature, safety, project, board, electric, leds, led, thonny, python, micropython, os, ide, onewire, ds18b20, circuitpython, review, launch, measure, probe, rp2040, specs, specifications, how to, guide, programming, Pico emulation, retro games raspberry pi pico, etaprime, eta prime, raspberry pi pico, arm cortex m0+, low cost
Id: DJdUjjOmyx8
Channel Id: undefined
Length: 5min 52sec (352 seconds)
Published: Sun Feb 13 2022
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.