Memory leaks in Rust occur when you intentionally leak memory using std::mem::forget or create reference cycles with Rc and RefCell that the garbage collector cannot break. To avoid leaks, ensure you drop references explicitly or use Weak pointers to break cycles in reference-counted smart pointers.
use std::rc::{Rc, Weak};
use std::cell::RefCell;
struct Node {
value: i32,
next: Option<Rc<RefCell<Node>>>,
parent: Weak<RefCell<Node>>,
}
fn main() {
let node = Rc::new(RefCell::new(Node {
value: 5,
next: None,
parent: Rc::downgrade(&Rc::new(RefCell::new(Node { value: 0, next: None, parent: Weak::new() }))),
}));
// Memory is freed when 'node' goes out of scope because the cycle is broken by 'Weak'
}