Static reference to a type causing fatal error (Windows)


#1

Hi everyone,

I need to implement a function in Rust which stores a raw pointer to a type (wrapped inside an Arc<Mutex<>>) in a static variable so that the function can later use that type by simply being called from any other function.

For some reason, the following code is displaying the stored type’s fields as expected but the program is being forced to close by Windows. I did not test it on other platforms.

Note that I am aware of other alternatives such as avoiding static variables by passing a reference to my type, etc. I just want to know what is going wrong with this specific implementation.

use std::sync::Arc;
use std::sync::Mutex;

fn glb(p_data: Option<MyType>) {
	
	static mut SHARED_TYPE_PTR: *const Arc<Mutex<MyType>> = 0 as *const Arc<Mutex<MyType>>;
	
	if p_data.is_some() {
		
		unsafe { 
			
			SHARED_TYPE_PTR = &Arc::new(Mutex::new(p_data.unwrap())) as *const Arc<Mutex<MyType>>; 
		}
		
	} else {
		
		unsafe {
			
			let shared_type_arc_ref: &Arc<Mutex<MyType>> = &*SHARED_TYPE_PTR;
			let arc_clone = shared_type_arc_ref.clone();
			let shared_type_guard = arc_clone.lock().unwrap();
			println!("{}, {}", shared_type_guard.f1, shared_type_guard.f2);
		}
	}
}

struct MyType {
	
	f1: i32,
	f2: i32,
}


fn some_func() {
	
	glb(None);
	//glb(None);
}

fn main() {
	
	glb(Some(MyType {f1: 4, f2: -7}));
	some_func();
}

Your help would be greatly appreciated!


#2

here you store pointer to variable on stack, so obviously your code should have random crashes,
or I missed something?

You need something like Box into_raw, or Arc into_raw (unstable feature)


#3

Hello @Dushistov. Thank you for your answer. I guess I’d better stick with lazy_static for now. Might well explore the into_raw option later on.

Thanks again