Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Memory Management Across Languages with Simple Analogies | A Large Scale Analysis of Borrow Pattern in Rust
 Dec 5, 2024 
    330 views 
 Written by Prashant Basnet
 👋 Welcome to my Signature, a space between logic and curiosity.
I’m a Software Development Engineer who loves turning ideas into systems that work beautifully.
This space captures the process: the bugs, breakthroughs, and “aha” moments that keep me building. 
 
Let's look at how memory is managed in multiple languages first.
Imagine you're renting bikes from a shop:
C/C++: Manual Memory Management
#include <stdlib.h> #include <stdio.h> int main() { int* num = (int*)malloc(sizeof(int)); // Allocate memory *num = 42; printf("Number: %d\n", *num); // free(num); // If you forget this, it causes a memory leak return 0; }Java/Python: Garbage Collection
You rent bikes, but there's an assistant who watches when bikes are not used and automatically returns them.
public class Main { public static void main(String[] args) { String data = new String("Hello, World!"); System.out.println(data); // Java's garbage collector will clean up `data` automatically } }Rust: Ownership and Borrowing:
The bike shop assigns each bike to one specific person (owner).
The shop ensures all bikes are accounted for when customers leave.
fn main() { // A bike is assigned to the first owner. let bike = String::from("Mountain Bike"); // Ownership created println!("First owner has the bike: {}", bike); // Transfer ownership to a new person. let new_owner = bike; // Ownership moved // println!("{}", bike); // Error: `bike` is no longer valid. println!("Ownership transferred to new person: {}", new_owner); // Borrow the bike temporarily (read-only). let borrowed_bike = &new_owner; // Immutable borrow println!("The bike is borrowed temporarily: {}", borrowed_bike); // Borrowing ends, and the bike remains with the new owner. }