Created
January 2, 2026 21:53
-
-
Save MicroDevX/06d8ccf1cf56aafdacea611f0e314bab to your computer and use it in GitHub Desktop.
Hello, Memory Safety
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| fn main() { | |
| let s1 = String::from("hello"); | |
| let s2 = s1; // s1 is "moved" to s2 here | |
| // println!("{}", s1); | |
| // ^ Un-commenting the line above would cause a compile error! | |
| // This prevents "double-free" memory bugs. | |
| println!("{}", s2); // This works perfectly. | |
| } |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Understanding Rust's Memory Protection
Rust’s primary "selling point" is providing memory safety without a garbage collector. It achieves this through three core pillars: Ownership, Borrowing, and Lifetimes.
1. The Ownership System
In Rust, every value has a variable called its owner. There can only be one owner at a time. When the owner goes out of scope, the memory is automatically returned.
Copy vs. Move: For simple types (like integers), data is copied. For complex types (like Strings), the data is moved.
Preventing Double-Free: Because there is only one owner, Rust prevents the "double-free" error, where the computer tries to clean up the same memory twice, leading to crashes or security vulnerabilities.
2. Borrowing (References)
You don't always want to take ownership of a value. Rust allows you to "borrow" a value using references (&).
Rust enforces two strict rules for borrowing, known as the Aliasing Model:
You can have any number of immutable references (&T).
OR you can have exactly one mutable reference (&mut T).
This prevents Data Races at compile time. If one part of your code is reading data, Rust ensures no other part can change it at the same time.
3. The Borrow Checker
The "Borrow Checker" is the part of the Rust compiler that enforces these rules. It looks at your code and ensures that:
References always point to valid memory.
You never have a Dangling Pointer (a reference to memory that has already been deallocated).
4. Lifetimes: Preventing Dangling References
Sometimes the compiler needs help understanding how long a reference should stay valid. Lifetimes are a way of telling the compiler: "This reference will live at least as long as this other piece of data."
Most of the time, Rust handles this automatically through "Lifetime Elision," but for complex functions, you might see syntax like <'a>, which acts as a label for a scope.