Skip to content

Instantly share code, notes, and snippets.

@imos
Last active July 17, 2023 11:54
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save imos/daf2fdbab8f33bd05a51fc12f017b579 to your computer and use it in GitHub Desktop.
Save imos/daf2fdbab8f33bd05a51fc12f017b579 to your computer and use it in GitHub Desktop.
Memory leak in Rust (Create circular reference using Arc/Mutex)
use std::sync::{Arc, Mutex};
struct Data{ data: Option<Arc<Mutex<Data>>> }
fn main() {
for _ in 0..5000000 {
let val = Arc::new(Mutex::new(Data{
data: Some(Arc::new(Mutex::new(Data { data: None })))
}));
let mut child = Arc::new(Mutex::new(Data{ data: None }));
let val_data = val.lock().unwrap();
if let Some(ref child_ref) = val_data.data {
child = child_ref.clone();
}
child.lock().unwrap().data = Some(val.clone());
}
println!("done");
loop {}
}
@gordonhart
Copy link

Thanks for posting! In case anybody else ends up here who has a hard time parsing this (like me), here's a significantly pared down example:

use std::sync::{Arc, Mutex};

struct Data(Option<Arc<Mutex<Data>>>);

fn main() {
    for _ in 0..5000000 {
        let val = Arc::new(Mutex::new(Data(None)));
        val.lock().unwrap().0 = Some(val.clone());
    }
    println!("done");
    loop {}
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment