[−][src]Function tao_of_rust::ch13::security_abstract::unbound_lifetime
pub fn unbound_lifetime()
未绑定生命周期(Unbound Lifetime)
未绑定生命周期(Unbound Lifetime),即可以被随意推断的生命周期, 在Unsafe中很容易产生,导致跳过Rust借用检查,而产生UB风险。
Basic usage: 产生未绑定生命周期的情况
在Debug模式下正常,但是在Release下会产生UB
fn foo<'a>(input: *const u32) -> &'a u32 { unsafe { return &*input // 等价于&(*input) } } fn main() { let x; { let y = 42; x = foo(&y); } println!("hello: {}", x); }Run
Basic usage: 另一种产生未绑定生命周期的情况
在Debug模式下正常,但是在Release下会产生UB
use std::mem::transmute; fn main() { let x: &i32; { let a = 12; let ptr = &a as *const i32; x = unsafe { transmute::<*const i32, &i32>(ptr) }; } println!("hello {}", x); }Run