Last active
July 17, 2023 11:54
-
-
Save imos/daf2fdbab8f33bd05a51fc12f017b579 to your computer and use it in GitHub Desktop.
Memory leak in Rust (Create circular reference using Arc/Mutex)
This file contains 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
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 {} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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: